我正在使用python的多处理模块来生成新进程
如下 :
import multiprocessing
import os
d = multiprocessing.Process(target=os.system,args=('iostat 2 > a.txt',))
d.start()
Run Code Online (Sandbox Code Playgroud)
我想获取iostat命令的pid或使用多处理模块执行的命令
当我执行:
d.pid
Run Code Online (Sandbox Code Playgroud)
它给了我运行此命令的子shell的pid.
任何帮助都是有价值的.
提前致谢
我正在使用 Python 使用 subprocess 模块调用 C++ 程序。由于程序需要一些时间来运行,我希望能够使用 Ctrl+C 来终止它。我在 StackOverflow 上看到了一些关于此的问题,但似乎没有一个解决方案对我有用。
我想要的是在 KeyboardInterrupt 上终止子进程。这是我拥有的代码(类似于其他问题中的建议):
import subprocess
binary_path = '/path/to/binary'
args = 'arguments' # arbitrary
call_str = '{} {}'.format(binary_path, args)
proc = subprocess.Popen(call_str)
try:
proc.wait()
except KeyboardInterrupt:
proc.terminate()
Run Code Online (Sandbox Code Playgroud)
但是,如果我运行它,代码会挂起,等待进程结束并且永远不会注册 KeyboardInterrupt。我也尝试了以下方法:
import subprocess
import time
binary_path = '/path/to/binary'
args = 'arguments' # arbitrary
call_str = '{} {}'.format(binary_path, args)
proc = subprocess.Popen(call_str)
time.sleep(5)
proc.terminate()
Run Code Online (Sandbox Code Playgroud)
此代码片段在终止程序时工作正常,因此问题不是发送到终止的实际信号。
如何更改代码以便子进程可以在 KeyboardInterrupt 上终止?
我正在运行 Python 2.7 和 Windows 7 64 位。提前致谢!
我尝试过的一些相关问题: