其他语言( C++ 、 Clojure 、 TypeScript ,也许是其他语言)也有类似的问题,但我仍在寻找 Python 的答案。
使用import
相关的类似问题还有很多和 global
在 Python 中,但相关的答案不符合我的需要。我只想将一个大文件拆分成小文件,以便在同一程序的不同版本中轻松修改/重用部分代码,而无需处理不同的命名空间或管理全局变量。
做我想做的一个简单的技巧是在运行时将选定的 Python 文件与脚本合并,但我希望有一种 Pythonic 的方式来做到这一点。
通过一个插图,我想要做的是从几个几乎相同的大文件中获取:
big_file_v1.py
## First part
# Hundreds of code lines to define things, make computations...
## Second part
# More code to do a few additional things
big_file_v2.py
## First part
# Exactly the same first part as in big_file_v1.py
## Second part
# A lot of small differences compared to big_file_v1.py
...到几个较小的文件,其中大多数不需要任何修改或只需要我想在所有不同版本中共享的修改:
myprog_v1.py
include first_part_common_to_both_versions.py
include second_part_v1.py
myprog_v2.py
include first_part_common_to_both_versions.py
include second_part_v2.py
在第二种情况下,使用
include
-like 命令,我可以立即分享在 first_part_common_to_both_versions.py
中所做的修改在我的程序的第 1 版和第 2 版中,我只需要修改/复制较小的文件 second_part_v2.py
如果我想进行新的修改/创建另一个新版本。问题是:如何做到这一点
include
在 Python 中?为了避免关于良好软件开发实践的争论,我使用 Python 作为解决科学问题的工具,因此,我更关心编辑舒适度而不是编码实践。
最佳答案
看看 exec 或 execfile:
"Python's exec statement is similar to the import statement, with an important difference: The exec statement executes a file in the current namespace. The exec statement doesn't create a new namespace. We'll look at this in the section called “The exec Statement”
关于python - 在共享相同命名空间的多个文件中拆分 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47928796/