用python将SIGINT发送到os.system

2024-04-18 20:33:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python中的os.system()运行Linux命令strace -c ./client。当我按ctrl+c时,我在终端上得到一些输出。我必须在一分钟后以编程方式发送ctrl+c信号,并希望终端输出是在文件中按ctrl+c后产生的。 伪脚本将非常有用。如果我使用subprocess.Popen,然后从键盘发送ctrl+c信号,我在终端上没有得到输出,因此必须使用os.system


Tags: 文件命令脚本client终端信号oslinux
2条回答

在Python中,可以使用os.kill编程发送Ctrl+C信号。问题是,您需要接收信号的进程的pid,而os.system不会告诉您任何有关这方面的信息。你应该用subprocess来表示。我不太明白你说的在终端上得不到输出。

不管怎样,你可以这样做:

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命令。在这种情况下,SIGINT信号(相当于Ctrl-C键盘中断)可以使用Popen.send_signal(signal.SIGINT)函数以编程方式发送到命令。函数的作用是:输出。例如

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
..

相关问题 更多 >