split python source code into multiple files?

后端 未结 4 1659
轮回少年
轮回少年 2021-01-30 08:02

I have a code that I wish to split apart into multiple files. In matlab one can simply call a .m file, and as long as it is not defined as anything in particular it

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-30 09:02

    You can do the same in python by simply importing the second file, code at the top level will run when imported. I'd suggest this is messy at best, and not a good programming practice. You would be better off organizing your code into modules

    Example:

    F1.py:

    print "Hello, "
    import f2
    

    F2.py:

    print "World!"
    

    When run:

    python ./f1.py
    Hello, 
    World!
    

    Edit to clarify: The part I was suggesting was "messy" is using the import statement only for the side effect of generating output, not the creation of separate source files.

提交回复
热议问题