Is it possible to run function in a subprocess without threading or writing a separate file/script.(是否可以在子进程中运行函数而无需线程或编写单独的文件/脚本.)
问题描述
import subprocess
def my_function(x):
return x + 100
output = subprocess.Popen(my_function, 1) #I would like to pass the function object and its arguments
print output
#desired output: 101
我只找到了有关使用单独脚本打开子进程的文档.有谁知道如何传递函数对象,甚至是传递函数代码的简单方法?
I have only found documentation on opening subprocesses using separate scripts. Does anyone know how to pass function objects or even an easy way to pass function code?
推荐答案
我认为您正在寻找更像多处理模块的东西:
I think you're looking for something more like the multiprocessing module:
http://docs.python.org/library/multiprocessing.html#the-process-class
子进程模块用于生成进程并使用它们的输入/输出执行操作 - 不用于运行函数.
The subprocess module is for spawning processes and doing things with their input/output - not for running functions.
这是您的代码的 multiprocessing 版本:
Here is a multiprocessing version of your code:
from multiprocessing import Process, Queue
# must be a global function
def my_function(q, x):
q.put(x + 100)
if __name__ == '__main__':
queue = Queue()
p = Process(target=my_function, args=(queue, 1))
p.start()
p.join() # this blocks until the process terminates
result = queue.get()
print result
这篇关于是否可以在子进程中运行函数而无需线程或编写单独的文件/脚本.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在子进程中运行函数而无需线程或编写单独的文件/脚本.
基础教程推荐
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
