Python3.5 subprocess 运行 不使用 shell 的 cat 命令
Python3.5 subprocess run cat command without using shell
我正在运行 cat
命令使用subprocess.run()
读取Linux版本。但是它不起作用,错误是:cat: '/etc/*-release': No such file or directory
,出于安全原因我不能使用 shell=True
。任何有关如何解决此问题的提示都将受到赞赏。
这是我的代码:
try:
result = subprocess.run(
shlex.split("cat /etc/*-release"),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
except subprocess.TimeoutExpired as err:
result = err
这就是 shell 评估 *
的作用。如果你不会使用它,你需要自己做,glob
可以帮助你。
因此您可以通过以下方式修复您的示例:
from glob import glob
try:
result = subprocess.run(
["cat"] + glob("/etc/*-release"),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
except subprocess.TimeoutExpired as err:
result = err
您可以使用 bash 命令以便计算 *:
process = subprocess.run(['bash', '-i', '-c', 'cat /etc/*-release'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
我正在运行 cat
命令使用subprocess.run()
读取Linux版本。但是它不起作用,错误是:cat: '/etc/*-release': No such file or directory
,出于安全原因我不能使用 shell=True
。任何有关如何解决此问题的提示都将受到赞赏。
这是我的代码:
try:
result = subprocess.run(
shlex.split("cat /etc/*-release"),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
except subprocess.TimeoutExpired as err:
result = err
这就是 shell 评估 *
的作用。如果你不会使用它,你需要自己做,glob
可以帮助你。
因此您可以通过以下方式修复您的示例:
from glob import glob
try:
result = subprocess.run(
["cat"] + glob("/etc/*-release"),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
except subprocess.TimeoutExpired as err:
result = err
您可以使用 bash 命令以便计算 *:
process = subprocess.run(['bash', '-i', '-c', 'cat /etc/*-release'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)