如何将值从子脚本传递到同时运行的父脚本?
在 Python 中提前向调用进程返回一个值?
您好,我想问是否有一种方法可以让一个脚本调用另一个脚本,让这两个脚本同时运行,并让子脚本在子脚本运行完成之前很久向父脚本发送一个值(没有提前退出该子脚本)?我正在寻找 Python 中的解决方案,但任何信息或线索都会有帮助,谢谢。
我认为一种方法是将要发送回父脚本的值打印到标准输出,然后让父脚本重定向它或以某种方式拾取它,但必须有更好的解决方案,因为如果子脚本打印其他内容怎么办? (然后父脚本必须知道如何使用 Unix head 和 tail 命令之类的东西隔离输出的确切部分,如果您根本不想使用标准输出怎么办?)
我已经搜索了有关此问题的答案,但我找不到任何。
Return a value early to a calling process in Python?
Hello, I want to ask is there a way to have one script call another script, have both those scripts running at the same time, and have the child script send a value to the parent script long before that child script is done running (WITHOUT exiting that child script early)? I'm looking for a solution in Python, but any information or clues would help, thankyou.
I think one way to do this is to print the value that you want to send back to the parent script to the standard output and then have the the parent script redirect it or pick it up some how, but there must be a better solution, because what if the child script prints other things? (then the parent script has to know how to isolate that exact part of the output with something like Unix head and tail commands, and what if you don't want to use the standard output at all?)
I have searched for answers on this, but I cannot find any.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 multiprocessing 从父脚本启动子脚本。
mp.Queue 可用于传递输出从子脚本返回到父脚本。这是一个简单的示例:
parent.py:
child.py:
请注意,
结果
通过了队列
必须是可腌制的。You could use multiprocessing to launch the child script from the parent script.
A mp.Queue could be used to communicate output from the child script back to the parent. Here is a simple example:
parent.py:
child.py:
Note that the
result
passed through thequeue
must be picklable.最好使用 多处理模块 这是正是为了这个目的而设计的。
It is probably best to use the multiprocessing module which is designed for exactly this purpose.