如果我在终端中以用户root
的身份键入此命令,例如用户bob
:
su - bob -c "cd /home ; ping www.google.com"
它会持续ping,直到我按CTRL+c
为止。我正在尝试模仿类似的行为。我的安装脚本会先运行,然后才能安装pexpect和其他东西。由于su - bob
,ping在子进程的子进程中运行。这意味着Popen.kill()
不起作用。我已经进行了一些研究,并在SO上找到了一些与PID分组然后杀死该组的答案。
问题:我想了解为什么communicate
不发送CTRL+c
并杀死我期望的子流程,这表明我不了解某些基本知识。>
import time
import subprocess
user = 'bob'
cmd_list = ['su', '-', user, '-c','cd /home/ ; ping www.google.com ; exit']
p = subprocess.Popen(
cmd_list,
stdin=subprocess.PIPE,
)
print("Wait 2s...")
time.sleep(2)
print("2s passed.")
try:
# Send CTRL+c to kill the child process from su -
p.communicate(input='\0x03', timeout=3)
print("CTRL+c killed the process")
except subprocess.TimeoutExpired:
print('Timeout occured')
p.kill()
答案 0 :(得分:2)
.communicate
使用stdin
,您需要使用send_signal
发送信号。
尝试一下:
import time
import subprocess
import signal
user = 'bob'
cmd_list = ['su', '-', user, '-c','cd /home/ ; ping www.google.com ; exit']
p = subprocess.Popen(
cmd_list,
stdin=subprocess.PIPE,
)
print("Wait 2s...")
time.sleep(2)
print("2s passed.")
try:
# Send CTRL+c to kill the child process from su -
p.send_signal(signal.SIGINT)
print("CTRL+c killed the process")
except subprocess.TimeoutExpired:
print('Timeout occured')
p.kill()