我正在尝试访问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作为脚本运行。
发布于 2020-12-02 22:07:22
当您使用os.system
时,它将指定的命令作为一个完全独立的进程运行。您需要通过某种操作系统级别的通信机制来传递变量: stdout、套接字、共享内存等。
但由于这两个脚本都是Python,因此只使用import OtherCode
会容易得多。(不过请注意,您需要在包中设置OtherCode.py
,以便Python知道它可以被import
编辑。)
发布于 2020-12-02 22:13:49
您可以使用runpy
模块将模块作为__main__
导入,然后从返回的字典中提取变量:
import runpy
vars = runpy.run_module("OtherCode", run_name="__main__")
desired_var = vars["var"] # where "var" is the variable name you want
发布于 2020-12-03 20:44:24
虽然这个修复可能不是很理想(或者是人们在谷歌上搜索的结果),但我最终打印出了变量,然后使用子进程将stdout作为变量:
MyCode.py
cmd = 'python OtherCode.py'
cmdOutput = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout
OtherCode.py
if __name__ == "__main__":
var = 'This is the variable I want to access'
print(var)
在本例中,cmdOutput ==变量
https://stackoverflow.com/questions/65116810
复制