python - 访问 __main__ 中的变量
问题描述
我正在尝试从作为脚本运行的 python 模块访问变量。变量定义在if __name__ == "__main__"
:
我正在使用的代码如下所示:
MyCode.py
cmd = 'python OtherCode.py'
os.system(cmd) # Run the other module as a python script
OtherCode.py
if __name__ == "__main__":
var = 'This is the variable I want to access'
我想知道是否有一种方法可以访问此变量,同时仍将 OtherCode.py 作为脚本运行。
解决方案
当您使用os.system
时,它会将指定的命令作为一个完全独立的进程运行。您需要通过某种操作系统级别的通信机制来传递变量:标准输出、套接字、共享内存等。
但由于这两个脚本都是 Python,因此只需import OtherCode
. (但请注意,您需要OtherCode.py
在包内进行设置,以便 Python 知道它可以被import
编辑。)