Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

return value from one python script to another

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 actually runs script2.py through os.

script1.py:

import os
print(os.system("script2.py 34"))

script2.py

import sys
def main():
    x="Hello World"+str(sys.argv[1])
    return x

if __name__ == "__main__":
    x= main()

As you can see, I am able to get the value into script2, but not back to script1. How can I do that? NOTE: script2.py HAS to be called as if its a commandline execution. Thats why I am using os.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...