【问题标题】:Using "<<<" with subprocess module将“<<<”与子进程模块一起使用
【发布时间】:2019-06-17 05:41:15
【问题描述】:

我在 python 2.7 中使用 subprocess 模块时遇到问题。 问题是当我尝试在我的命令中使用

这是一个简化的例子:

#!/usr/bin/python
import subprocess

command="cat <<< 'hi there'"
print subprocess.check_output(command.split(" "))

结果:

cat: '<<<': Aucun fichier ou dossier de ce type
cat: "'hi": Aucun fichier ou dossier de ce type
cat: "there'": Aucun fichier ou dossier de ce type
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    print subprocess.check_output(command.split(" "))
  File "/usr/lib/python2.7/subprocess.py", line 219, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['cat', '<<<', "'hi", "there'"]' returned non-zero exit status 1

我对这个结果感到困惑。为什么当我尝试使用

【问题讨论】:

    标签: bash python-2.7 subprocess


    【解决方案1】:

    &lt;&lt;&lt; 运算符是一个 bash 构造。您没有在命令中使用 bash,因此它不起作用。尝试添加shell=True

    另外,如果你在空格中分割你的命令,你会得到非常奇怪的参数(检查错误信息)。如果字符串必须由 bash 解释,请不要乱用它:

    #!/usr/bin/python
    import subprocess
    
    command="cat <<< 'hi there'"
    print subprocess.check_output(command, shell=True, executable="/bin/bash")
    

    【讨论】:

    • 事实上,
    • 我用executable 详细信息更新了答案。如果那回答了您的问题...接受它! :-)
    猜你喜欢
    • 2014-02-24
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 2016-10-09
    相关资源
    最近更新 更多