簡體   English   中英

使用system()命令從另一個python腳本執行時,如何訪問python腳本中變量的值?

[英]How to access the value of a variable in a python script when executed from another python script using system() command?

我有一個python scriptparent_script.py ),該python script使用system()命令執行另一個python scriptchild_script.py )。 在此python腳本中,有一個變量( var1 ),我想返回其值或在parent_script.py腳本中訪問。 我當前的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()  

我當前的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)  

如何獲取返回或訪問在parent_script.py中的var1的值?

注意:我知道使用子進程可以執行python腳本並獲取var1的值,但是在這種情況下,我只能使用system()來執行python腳本。 child_script中的var1值也顯示為虛擬值。 實際值是由其上方的代碼生成的,由於與該代碼無關,因此未顯示。

由於您使用的是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

然后,您可以正常使用var1 (這假定global var1放在func1()的開頭。)

但是請注意, execfile()在Python3中不存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM