from subprocess import Popen, PIPE, STDOUT
def exe_command(command):
# 为什么要写一个这么复杂的函数?
# 在实际使用中发现,很多方法需要ctrl c掉,但是他的进程还在后台运行,使用 process.kill()也无法杀死进程,查询发现是Popen 创建了一个子进程去执行命令,process.kill() 只是杀死了Popen本身的进程,所以使用下面的笨方法去获取真正的进程然后kill,之后谁有更好的方法,希望指正
process = Popen(command, stdout=PIPE, stderr=STDOUT, shell=True)
try:
result = []
with process.stdout:
for line in iter(process.stdout.readline, b''):
print(line.decode().strip())
result.append(line.decode().strip())
process.wait()
return process, result
except KeyboardInterrupt:
get_pid_cmd = """ps -ef | grep "%s" | grep -v grep | awk '{print $2}'""" % command[:10]
_, result = exe_command(get_pid_cmd)
kill_cmd = f"kill -9 {process.pid} {result[0]}"
print(f"kill -9 {process.pid} {result[0]}")
exe_command(kill_cmd)
python执行shell命令并实时输出信息
于 2022-01-28 21:18:29 首次发布