在子流程模块中使用“ <<<”

时间:2019-01-23 15:25:24

标签: bash python-2.7 subprocess

我在python 2.7中使用子过程模块遇到问题。 问题是当我尝试在命令中使用<<<时。

这是一个简化的示例:

#!/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命令都有效,除了当我使用“ <<<”:/

1 个答案:

答案 0 :(得分:0)

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

此外,如果在空格中分割命令,则会得到非常奇怪的参数(请检查错误消息)。如果必须使用bash解释字符串,请不要将其弄乱:

#!/usr/bin/python
import subprocess

command="cat <<< 'hi there'"
print subprocess.check_output(command, shell=True, executable="/bin/bash")
相关问题