如何 return 来自主函数的字符串?
How to return string from main function?
如何在此脚本中获取 return 字符串?
main.py
from subprocess import Popen, PIPE
import os
import sys
child = os.path.join(os.path.dirname(__file__), "child.py")
command = [sys.executable, child, "test"]
process = Popen(command, stdout=PIPE, stdin=PIPE)
process.communicate()
print(process.poll())
child.py
import sys
def main(i):
return i*3
if __name__ == '__main__':
main(*sys.argv[1:])
我只得到0。
我认为从 print()
和 process.communicate()
获得回应不是最好的方式。
进程不能 return 函数可以具有相同意义的值。
他们只能设置退出代码(即您得到的 0)。
但是,您可以使用 stdin 和 stdout 在主脚本和 child.py
之间进行通信。
要“return”来自 child 的内容,只需打印您想要的值 return。
# child.py
print("Hello from child")
parent 会做这样的事情:
process = Popen(command, stdout=PIPE, stdin=PIPE)
stdout, stderr = Popen.communicate()
assert stdout == "Hello from child"
如何在此脚本中获取 return 字符串?
main.py
from subprocess import Popen, PIPE
import os
import sys
child = os.path.join(os.path.dirname(__file__), "child.py")
command = [sys.executable, child, "test"]
process = Popen(command, stdout=PIPE, stdin=PIPE)
process.communicate()
print(process.poll())
child.py
import sys
def main(i):
return i*3
if __name__ == '__main__':
main(*sys.argv[1:])
我只得到0。
我认为从 print()
和 process.communicate()
获得回应不是最好的方式。
进程不能 return 函数可以具有相同意义的值。
他们只能设置退出代码(即您得到的 0)。
但是,您可以使用 stdin 和 stdout 在主脚本和 child.py
之间进行通信。
要“return”来自 child 的内容,只需打印您想要的值 return。
# child.py
print("Hello from child")
parent 会做这样的事情:
process = Popen(command, stdout=PIPE, stdin=PIPE)
stdout, stderr = Popen.communicate()
assert stdout == "Hello from child"