Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

linux - Send SIGINT in python to os.system

I am trying to run a Linux command strace -c ./client in python with os.system(). When i press ctrl+c i get some output on the terminal.I have to send the ctrl+c signal programmatically after one minute and want the terminal output that is produced after pressing ctrl+c in a file. A pseudo script will be really helpful.If i use subprocess.Popen and then send ctrl+c signal from keyboard i didn't get output on the terminal,so have to use os.system

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Python, you could programatically send a Ctrl+C signal using os.kill. Problem is, you need the pid of the process that'll receive the signal, and os.system does not tell you anything about that. You should use subprocess for that. I don't quite get what you said about not getting the output on the terminal.

Anyways, here's how you could do it:

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...