Return value from one python script to another

I have two files: script1.py and script2.py. I need to call script2.py from script1.py and return the value from script2.py back to script1.py. But catch - 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 can get the value in script2, but not return to script1. How can i do this? NOTE: script2.py HAS must be invoked as if it were command line execution. That is why I use os.

+6
source share
2 answers

Well, if you understood correctly what you want:

  • pass argument to another script
  • get output from another script to the original caller

I recommend using the subprocess module. The easiest way is to use the check_output () function.

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

Example 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]) 
+12
source

The recommended way to return a value from one python "script" to another is to import the script as a Python module and directly call the functions:

 import another_module value = another_module.get_value(34) 

where another_module.py :

 #!/usr/bin/env python def get_value(*args): return "Hello World " + ":".join(map(str, args)) def main(argv): print(get_value(*argv[1:])) if __name__ == "__main__": import sys main(sys.argv) 

You can import another_module and run it as a script from the command line. If you do not need to run it as a command line script, you can remove the main() function and if __name__ == "__main__" .

See also Call python script with input using python script with subprocess .

+2
source

Source: https://habr.com/ru/post/988572/


All Articles