[英]How to access the value of a variable in a python script when executed from another python script using system() command?
I have a python script
( parent_script.py ) which executes another python script
( child_script.py ) using system()
command. 我有一个python script
( parent_script.py ),该python script
使用system()
命令执行另一个python script
( child_script.py )。 In this python script there is a variable( var1
) whose value I want to return to or access in the parent_script.py script. 在此python脚本中,有一个变量( var1
),我想返回其值或在parent_script.py脚本中访问。 My current parent_script.py is: 我当前的parent_script.py是:
def call_script():
cmd = "/usr/local/bin/python2.7 child_script.py --arg1 arg1 --arg2 arg2"
output_code = system(cmd)
if output_code != 0:
print(strerror(output_code) + ' \n')
sys.exit(1)
# Get the value of var1 in child_script.py
if __name__ == '__main__':
call_script()
My current child_script.py is: 我当前的child_script.py是:
def func1():
# bunch of other code
var1 = '2015' # this is the value that I want to access in parent_script.py
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Child Script')
parser.add_argument('--arg1', required=True)
parser.add_argument('--arg2', required=True)
args = parser.parse_args()
func1(args)
How can I get the value of var1
returned to or accessed in parent_script.py? 如何获取返回或访问在parent_script.py中的var1
的值?
Note: I know using subprocess I can execute the python script and get the value of var1 but in this case I am restricted to use system() only to execute the python script. 注意:我知道使用子进程可以执行python脚本并获取var1的值,但是在这种情况下,我只能使用system()来执行python脚本。 Also the value of var1 in child_script is shown as a dummy value. child_script中的var1值也显示为虚拟值。 Actual value is generated by the code that is above it and I haven't shown as it is not relevant. 实际值是由其上方的代码生成的,由于与该代码无关,因此未显示。
Since you are using python2.7
, use execfile()
instead of os.system()
: 由于您使用的是python2.7
,因此请使用execfile()
而不是os.system()
:
sys.argv[1:] = ["--arg1", "arg1", "--arg2", "arg2"]
try:
execfile("child_script.py")
except SystemExit as error:
output_code = error.code
else:
output_code = 0
Then you can use var1
normally. 然后,您可以正常使用var1
。 (This assumes that global var1
was put at the beginning of func1()
.) (这假定global var1
放在func1()
的开头。)
Note, though, that execfile()
does not exist in Python3. 但是请注意, execfile()
在Python3中不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.