"subprocess.Popen" - проверка на наличие ошибок и ошибок
Я хочу проверить, успешно ли завершено выполнение подпроцесса или нет. В настоящее время я нашел решение, но я не уверен, что оно правильное и надежное. Гарантируется ли, что каждый процесс выводит свои ошибки только в stderr с уважением к stdout
:
Примечание: меня не интересует просто перенаправление/распечатка вывода. Это я уже знаю, как это сделать.
pipe = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
if "" == pipe.stdout.readline():
print("Success")
self.isCommandExectutionSuccessful = True
if not "" == pipe.stderr.readline():
print("Error")
self.isCommandExectutionSuccessful = True
альтернативно:
if "" == pipe.stdout.readline():
print("Success")
self.isCommandExectutionSuccessful = True
else:
print("Error")
self.isCommandExectutionSuccessful = False
а также:
if not "" == pipe.stderr.readline():
print("Success")
self.isCommandExectutionSuccessful = True
else:
print("Error")
self.isCommandExectutionSuccessful = False
Ответы
Ответ 1
Вам нужно что-либо сделать с выходом процесса?
Здесь может быть полезен метод check_call
. См. Здесь документы python: https://docs.python.org/2/library/subprocess.html#subprocess.check_call
Затем вы можете использовать это следующим образом:
try:
subprocess.check_call(command)
except subprocess.CalledProcessError:
# There was an error - command exited with non-zero code
Однако это зависит от command
, возвращающего код завершения 0 для успешного завершения и ненулевое значение для ошибки.
Если вам нужно также захватить вывод, тогда метод check_output
может быть более уместным. По-прежнему можно перенаправить стандартную ошибку, если вам это тоже нужно.
try:
proc = subprocess.check_output(command, stderr=subprocess.STDOUT)
# do something with output
except subprocess.CalledProcessError:
# There was an error - command exited with non-zero code
Смотрите документы здесь: https://docs.python.org/2/library/subprocess.html#subprocess.check_output
Ответ 2
Вы можете проверить код возврата процесса, используя метод check_call().
В случае, если процесс возвратил ненулевое значение CalledProcessError, будет поднят.
Ответ 3
output,error=pipe.communicate()
Это будет ждать завершения команды и выдачи вывода или ошибки в зависимости от состояния команды.
Ответ 4
Полное решение с проверкой кода возврата, stdout и stderr:
import subprocess as sp
# ok
pipe = sp.Popen( 'ls /bin', shell=True, stdout=sp.PIPE, stderr=sp.PIPE )
# res = tuple (stdout, stderr)
res = pipe.communicate()
print("retcode =", pipe.returncode)
print("res =", res)
print("stderr =", res[1])
for line in res[0].decode(encoding='utf-8').split('\n'):
print(line)
# with error
pipe = sp.Popen( 'ls /bing', shell=True, stdout=sp.PIPE, stderr=sp.PIPE )
res = pipe.communicate()
print("retcode =", pipe.returncode)
print("res =", res)
print("stderr =", res[1])
Печать:
retcode = 0
res = (b'bash\nbunzip2\nbusybox\nbzcat\n...zmore\nznew\n', b'')
stderr = b''
bash
bunzip2
busybox
bzcat
...
zmore
znew
retcode = 2
res = (b'', b"ls: cannot access '/bing': No such file or directory\n")
stderr = b"ls: cannot access '/bing': No such file or directory\n"
Ответ 5
Вот как я это сделал наконец:
# Call a system process
try:
# universal_newlines - makes manual decoding of subprocess.stdout unnecessary
output = subprocess.check_output(command,
stderr=subprocess.STDOUT,
universal_newlines=True)
# Print out command standard output (elegant)
for currentLine in output:
self.textEdit_CommandLineOutput.insertPlainText(currentLine)
self.isCommandExecutionSuccessful = True
except subprocess.CalledProcessError as error:
self.isCommandExecutionSuccessful = False
errorMessage = ">>> Error while executing:\n"\
+ command\
+ "\n>>> Returned with error:\n"\
+ str(error.output)
self.textEdit_CommandLineOutput.append(errorMessage)
QMessageBox.critical(None,
"ERROR",
errorMessage)
print("Error: " + errorMessage)
except FileNotFoundError as error:
errorMessage = error.strerror
QMessageBox.critical(None,
"ERROR",
errorMessage)
print("Error: ", errorMessage)
Я надеюсь, что это будет полезно кому-то другому.