我正在制作一个程序,为Windows中的标准命令外壳添加附加功能。例如,键入google
后跟关键字将打开一个新标签,Google搜索这些关键字等。每当输入不引用我创建的自定义函数时,它就会使用subprocess.call(rawCommand, shell=True)
作为 shell 命令进行处理。
由于我想预测我的输入何时不是有效的命令并返回类似f"Invalid command: {rawCommand}"
的内容,我应该怎么做?
到目前为止,我已经尝试了subprocess.call(rawCommand)
它也返回标准输出和退出代码。所以它看起来像这样:
>>> from subprocess import call
>>> a, b = call("echo hello!", shell=1), call("xyz arg1 arg2", shell=1)
hello!
'xyz' is not recognized as an internal or external command,
operable program or batch file.
>>> a
0
>>> b
1
我想简单地收到该退出代码。关于我该如何做到这一点的任何想法?
如果你有一天想要处理编码错误,取回你正在运行的命令的结果,超时或决定 0 以外的哪些退出代码可能不会触发错误(我在看你,java 运行时!(,这里有一个完整的函数来完成这项工作:
import os
from logging import getLogger
import subprocess
logger = getLogger()
def command_runner(command, valid_exit_codes=None, timeout=300, shell=False, encoding='utf-8',
windows_no_window=False, **kwargs):
"""
Whenever we can, we need to avoid shell=True in order to preseve better security
Runs system command, returns exit code and stdout/stderr output, and logs output on error
valid_exit_codes is a list of codes that don't trigger an error
windows_no_window will hide the command window (works with Microsoft Windows only)
Accepts subprocess.check_output arguments
"""
# Set default values for kwargs
errors = kwargs.pop('errors', 'backslashreplace') # Don't let encoding issues make you mad
universal_newlines = kwargs.pop('universal_newlines', False)
creationflags = kwargs.pop('creationflags', 0)
if windows_no_window:
creationflags = creationflags | subprocess.CREATE_NO_WINDOW
try:
# universal_newlines=True makes netstat command fail under windows
# timeout does not work under Python 2.7 with subprocess32 < 3.5
# decoder may be unicode_escape for dos commands or utf-8 for powershell
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=shell,
timeout=timeout, universal_newlines=universal_newlines, encoding=encoding,
errors=errors, creationflags=creationflags, **kwargs)
except subprocess.CalledProcessError as exc:
exit_code = exc.returncode
try:
output = exc.output
except Exception:
output = "command_runner: Could not obtain output from command."
if exit_code in valid_exit_codes if valid_exit_codes is not None else [0]:
logger.debug('Command [%s] returned with exit code [%s]. Command output was:' % (command, exit_code))
if isinstance(output, str):
logger.debug(output)
return exc.returncode, output
else:
logger.error('Command [%s] failed with exit code [%s]. Command output was:' %
(command, exc.returncode))
logger.error(output)
return exc.returncode, output
# OSError if not a valid executable
except (OSError, IOError) as exc:
logger.error('Command [%s] failed because of OS [%s].' % (command, exc))
return None, exc
except subprocess.TimeoutExpired:
logger.error('Timeout [%s seconds] expired for command [%s] execution.' % (timeout, command))
return None, 'Timeout of %s seconds expired.' % timeout
except Exception as exc:
logger.error('Command [%s] failed for unknown reasons [%s].' % (command, exc))
logger.debug('Error:', exc_info=True)
return None, exc
else:
logger.debug('Command [%s] returned with exit code [0]. Command output was:' % command)
if output:
logger.debug(output)
return 0, output
用法:
exit_code, output = command_runner('whoami', shell=True)
一些 shell 具有语法检查模式(例如,bash -n
(,但这是唯一可以与"尝试执行命令并查看会发生什么"分开的错误形式。 定义一类更大的"即时"错误是一个令人担忧的命题:如果echo hello; ./foo
无效是因为找不到foo
作为命令,那么false && ./foo
呢,它永远不会尝试运行它,或者cp /bin/ls foo; ./foo
,哪个可能成功(或可能无法复制(? 那些可能会或可能不会操纵PATH
以找到foo
的eval $(configure_shell); foo
呢? 那么foo || install_foo
,可能会预料到故障呢?
因此,在任何有意义的意义上预测失败是不可能的:您唯一真正的选择是捕获命令的输出/错误(如注释中所述(并以某种有用的方式报告它们。