从一个 python 脚本返回值到另一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30664263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
return value from one python script to another
提问by codingsplash
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 和 script2.py。我需要从script1.py 调用script2.py 并将script2.py 中的值返回给script1.py。但问题是 script1.py 实际上通过 os 运行 script2.py。
script1.py:
脚本1.py:
import os
print(os.system("script2.py 34"))
script2.py
脚本2.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.
如您所见,我能够将值放入 script2,但不能返回到 script1。我怎样才能做到这一点?注意:script2.py 必须像命令行执行一样被调用。这就是为什么我使用 os.
采纳答案by ?ukasz Rogalski
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.
我会推荐使用 subprocess 模块。最简单的方法是使用check_output()函数。
Run command with arguments and return its output as a byte string.
运行带参数的命令并将其输出作为字节字符串返回。
Sample solution:
示例解决方案:
script1.py
脚本1.py
import sys
import subprocess
s2_out = subprocess.check_output([sys.executable, "script2.py", "34"])
print s2_out
script2.py:
脚本2.py:
import sys
def main(arg):
print("Hello World"+arg)
if __name__ == "__main__":
main(sys.argv[1])
回答by jfs
The recommended way to return a value from one python "script" to another is to import the script as a Python module and call the functions directly:
将值从一个 python “脚本”返回到另一个的推荐方法是将脚本作为 Python 模块导入并直接调用函数:
import another_module
value = another_module.get_value(34)
where another_module.py
is:
在哪里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 could both import another_module
and run it as a script from the command-line. If you don't need to run it as a command-line script then you could remove main()
function and if __name__ == "__main__"
block.
您可以another_module
从命令行将其作为脚本导入和运行。如果您不需要将它作为命令行脚本运行,那么您可以删除main()
函数和if __name__ == "__main__"
块。
See also, Call python script with input with in a python script using subprocess.