[英]Python Subprocess.Run not running Inkscape pdf to svg
[英]python 3.5 - subprocess.run still running after the script was terminated
為什么當我從該腳本運行subprocess.run('knife ec2 server create...', shell=True, check=True)
命令時,我用ctrl+c
終止python腳本后,控件返回到終端會話,但是幾分鍾/秒后,shell命令再次出現在終端會話中,並且subprocess.run
的shell命令仍在運行?
我想我在os.system
了同樣的問題,例如os.system('ping 8.8.8.8')
。
^C
Waiting for EC2 to create the instance.....^CTraceback (most recent call last):
File "t.py", line 177, in <module>
subprocess.run(command, shell=True, check=True)
File "/usr/lib/python3.5/subprocess.py", line 695, in run
stdout, stderr = process.communicate(input, timeout=timeout)
File "/usr/lib/python3.5/subprocess.py", line 1064, in communicate
self.wait()
File "/usr/lib/python3.5/subprocess.py", line 1658, in wait
(pid, sts) = self._try_wait(0)
File "/usr/lib/python3.5/subprocess.py", line 1608, in _try_wait
(pid, sts) = os.waitpid(self.pid, wait_flags)
KeyboardInterrupt
$ ..............................................................................done
SSH Target Address: ec2()
Doing old-style registration with the validation key at /etc/chef/validation.pem...
Delete your validation key in order to use your user credentials instead
我也嘗試了以下代碼,但出現錯誤:
command = ('knife ec2 server create -N ' + fullname + ' -f ' + instance_type + ' -i ' + pem_file)...
p = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE)
while True:
out = p.stderr.read(1)
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
錯誤:
`sys.stdout.write(out) TypeError: write() argument must be str, not bytes'
有沒有一種簡單的方法可以像Ruby
通過system()
使用python
運行shell命令?
謝謝
子流程模塊會產生一個新流程。 當您向python代碼發送CTRL + C信號時,您已經存在python應用程序,但是子進程仍在運行,並且您的代碼決定不等待該進程完成。
嘗試在代碼中捕獲Ctrl + C信號,然后在存在您的應用程序之前使用Popen終止調用來結束子進程。
import shlex, subprocess
command_line = input()
args = shlex.split(command_line)
print(args)
p = subprocess.Popen(args) # Success!
這是終止調用的API文檔:
編輯這是python 2.7的示例演示代碼,打印strout的代碼部分不適用於ping,因為它仍會將ping結果輸出到終端,但我將其放置在此處以供參考。
import subprocess
import signal
import sys
command = 'ping {0}'.format('8.8.8.8')
p = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE)
# callback for the Ctrl+C signal
def signal_handler(signal, frame):
print("CTRL+C received")
p.kill() # or terminate
p.wait()
sys.exit(0)
# register signal with the callback
signal.signal(signal.SIGINT, signal_handler)
# white subprocess hasn't finished
while p.poll() is None:
out = p.communicate()
print(out.stdoutdata)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.