How to send control C to Mac Terminal using python?

匆匆过客 提交于 2019-12-23 22:23:38

问题


I have a python script that needs to send control C to the mac terminal. I've tried sending the plain text "^C" but I get back that the terminal does not recognize the command. (The terminal meaning the pseudo terminal that python creates)

Basically, I am using the terminal to run an old Unix Executable and the only way that I can think of to terminate this gracefully is to send the interrupt signal. Is there any way I can fool the terminal into thinking that I pressed control C?

Thanks in advance!


回答1:


You can explicitly send the SIGINT signal to the process if you can get its PID using os.kill.

os.kill(pid, signal.SIGINT)

This will require you to instrument your script to grab the process PID, but it's the best way to emulate the "ctrl-c" behavior.




回答2:


If you open the process using subprocess's Popen, you should be able to send a control signal like this:

proc.send_signal(signal.SIGINT)

You'll need to import signal to get SIGINT.



来源:https://stackoverflow.com/questions/11570266/how-to-send-control-c-to-mac-terminal-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!