如何在 python 中作为子进程执行函数回调?
How to execute a funcion callback as subprocess in python?
出于这个(和其他一些)原因,我目前正在学习如何使用子流程
我买了一本书来学习如何使用子流程。这是一本好书
而且我在理解它方面没有困难。在我的书中,他们开始解释
如何将 shell 命令作为子进程执行。
我有一个编程问题困扰了我很长时间,有了子流程,我可以
能够解决它但是我需要作为子进程执行函数回调。
我有这段代码可以回显一些东西,但它是一个 shell 命令:
import subprocess
proc = subprocess.Popen(['echo', 'Hello, this is child process speaking'],
stdout=subprocess.PIPE, shell=True)
out, err = proc.communicate()
print(out.decode('utf-8'))
我希望此回调作为子进程执行:
def callb()
import time as t
print('2')
t.sleep(2)
print('1')
t.sleep(2)
print('0')
我只是试着像这样执行这个回调(这是一个简单天真的想法):
proc = subprocess.Popen(callb())
但这给了我以下错误:
Traceback (most recent call last):
File "/root/testfile.py", line 6, in <module>
proc = subprocess.Popen(callb())
File "/usr/lib/python3.3/subprocess.py", line 818, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.3/subprocess.py", line 1321, in _execute_child
args = list(args)
TypeError: 'NoneType' object is not iterable
奇怪的是,它确实执行了回调,但随后却引发了这个错误!
我做错了什么?我是不是忘记了什么?
subprocess
模块不适合执行 python 回调。你想看看 multiprocessing
module 。 Process
和 Pool
的前几个示例似乎可以满足您的要求。
出于这个(和其他一些)原因,我目前正在学习如何使用子流程 我买了一本书来学习如何使用子流程。这是一本好书 而且我在理解它方面没有困难。在我的书中,他们开始解释 如何将 shell 命令作为子进程执行。
我有一个编程问题困扰了我很长时间,有了子流程,我可以 能够解决它但是我需要作为子进程执行函数回调。
我有这段代码可以回显一些东西,但它是一个 shell 命令:
import subprocess
proc = subprocess.Popen(['echo', 'Hello, this is child process speaking'],
stdout=subprocess.PIPE, shell=True)
out, err = proc.communicate()
print(out.decode('utf-8'))
我希望此回调作为子进程执行:
def callb()
import time as t
print('2')
t.sleep(2)
print('1')
t.sleep(2)
print('0')
我只是试着像这样执行这个回调(这是一个简单天真的想法):
proc = subprocess.Popen(callb())
但这给了我以下错误:
Traceback (most recent call last):
File "/root/testfile.py", line 6, in <module>
proc = subprocess.Popen(callb())
File "/usr/lib/python3.3/subprocess.py", line 818, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.3/subprocess.py", line 1321, in _execute_child
args = list(args)
TypeError: 'NoneType' object is not iterable
奇怪的是,它确实执行了回调,但随后却引发了这个错误! 我做错了什么?我是不是忘记了什么?
subprocess
模块不适合执行 python 回调。你想看看 multiprocessing
module 。 Process
和 Pool
的前几个示例似乎可以满足您的要求。