return value from one python script to another

前端 未结 2 1457
鱼传尺愫
鱼传尺愫 2020-12-03 01:50

I have two files: script1.py and script2.py. I need to invoke script2.py from script1.py and return the value from script2.py back to script1.py. But the catch is script1.py

2条回答
  •  醉话见心
    2020-12-03 02:49

    Ok, if I understand you correctly you want to:

    • pass an argument to another script
    • retrieve an output from another script to original caller

    I'll recommend using subprocess module. Easiest way would be to use check_output() function.

    Run command with arguments and return its output as a byte string.

    Sample solution:

    script1.py

    import sys
    import subprocess
    s2_out = subprocess.check_output([sys.executable, "script2.py", "34"])
    print s2_out
    

    script2.py:

    import sys
    def main(arg):
        print("Hello World"+arg)
    
    if __name__ == "__main__":
        main(sys.argv[1])
    

提交回复
热议问题