将python中的SIGINT发送到os.system
我正试图在python中使用将python中的SIGINT发送到os.system,python,linux,os.system,Python,Linux,Os.system,我正试图在python中使用os.system()运行Linux命令strace-c./client。当我按下ctrl+c时,终端上会有一些输出。我必须在一分钟后以编程方式发送ctrl+c信号,并希望在文件中显示按下ctrl+c后生成的终端输出。 伪脚本将非常有用。如果我使用subprocess.Popen,然后从键盘发送ctrl+c信号,我在终端上没有得到输出,因此必须使用Python中的os.system,您可以使用编程发送ctrl+c信号。问题是,您需要接收信号的进程的pid,而os.sy
os.system()
运行Linux命令strace-c./client
。当我按下ctrl+c
时,终端上会有一些输出。我必须在一分钟后以编程方式发送ctrl+c
信号,并希望在文件中显示按下ctrl+c
后生成的终端输出。
伪脚本将非常有用。如果我使用
subprocess.Popen
,然后从键盘发送ctrl+c
信号,我在终端上没有得到输出,因此必须使用Python中的os.system
,您可以使用编程发送ctrl+c
信号。问题是,您需要接收信号的进程的pid
,而os.system
不会告诉您这方面的任何信息。为此,您应该使用子流程
。我不太明白你说的没有在终端上得到输出
不管怎样,你可以这样做:
import subprocess
import signal
import os
devnull = open('/dev/null', 'w')
p = subprocess.Popen(["./main"], stdout=devnull, shell=False)
# Get the process id
pid = p.pid
os.kill(pid, signal.SIGINT)
if not p.poll():
print "Process correctly halted"
我建议使用子流程python模块来运行linux命令。在这种情况下,可以使用Popen.send_signal(signal.SIGINT)函数以编程方式将SIGINT信号(相当于Ctrl-C键盘中断)发送到命令。函数将为您提供输出。比如说
import subprocess
import signal
..
process = subprocess.Popen(..) # pass cmd and args to the function
..
process.send_signal(signal.SIGINT) # send Ctrl-C signal
..
stdout, stderr = process.communicate() # get command output and error
..
在ubuntu 14.04 x64上,如果我运行python 2.7.6,我会得到一个属性错误(popen对象没有属性send_signal)。这是怎么回事?应该是
过程。send_signal(signal.CTRL_C_EVENT)
,signal.SIGINT raisevalue错误:不支持的信号:2
@RonenNessCTRL_C_EVENT
是Windows,SIGINT
是Linux。这个问题用Linux标记,因此答案是正确的。