我想使用从 bash 函数返回值的重定向到例如grep,并从 python 中调用它。
即使我使用的是 shell=True
在子流程中,这似乎不起作用。
在 bash 中工作的示例:
grep foo <(echo "fooline")
给出错误 /bin/sh: 1: Syntax error: "(" unexpected
的示例 在 python 3.7.3、Ubuntu 19.04 中:
#!/usr/bin/env python3
import subprocess
subprocess.call('grep foo <(echo "fooline")', shell=True)
根据类似 these 的回答,重定向应该与 shell=True 一起使用(它确实用于重定向实际文件,但不返回值)。
编辑: 添加了 shebang 和 python 版本。
最佳答案
您观察到的不一致是由于 shell=True
给您的是 sh
shell,而不是 bash
。
以下内容在 bash
中有效,但在 sh
中无效。
grep foo <(echo "fooline")
示例输出:
sh-3.2$ grep foo <(echo "fooline")
sh: syntax error near unexpected token `('
如果您使用有效的 sh
表达式,您的方法就会起作用。或者,您可以指定要与 executable='/bin/bash'
一起使用的 shell。您还可以使用类似的东西:
subprocess.Popen(['/bin/bash', '-c', cmd])
关于python - 在 python 中使用重定向运行 bash 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57249913/