简体   繁体   English

在python中使用重定向运行bash命令

[英]Running bash command with redirection in python

I want to use redirection from bash function return values to eg grep, and call it from python. 我想使用从bash函数返回值到grep的重定向,并从python调用它。

Even though I am using shell=True in subprocess, this does not seem to work. 即使我在子进程中使用shell=True ,这似乎也不起作用。

Example that works in bash: 在bash中工作的示例:

grep foo <(echo "fooline")

Example that gives the error /bin/sh: 1: Syntax error: "(" unexpected in python 3.7.3, Ubuntu 19.04: 给出错误/bin/sh: 1: Syntax error: "(" unexpected示例/bin/sh: 1: Syntax error: "(" unexpected在python 3.7.3,Ubuntu 19.04中/bin/sh: 1: Syntax error: "(" unexpected

#!/usr/bin/env python3
import subprocess
subprocess.call('grep foo <(echo "fooline")', shell=True)

According to answers like these , redirection should work with shell=True (and it does for redirecting actual files, but not return values). 根据类似这样的答案,重定向应该与shell = True一起使用(并且它确实用于重定向实际文件,但不返回值)。

EDIT : Added shebang and python version. 编辑 :添加了shebang和python版本。

The error is a shell error, nothing to do with python. 该错误是外壳错误,与python无关。 sh chokes on the parentheses of python syntax. sh扼杀了python语法的括号。

/bin/sh: 1: Syntax error: "(" unexpected / bin / sh:1:语法错误:“(”意外

Let's add a shebang (reference: Should I put #! (shebang) in Python scripts, and what form should it take? ) 让我们添加一个shebang(参考: 我应该在Python脚本中添加#!(shebang),它应该采用什么形式?

And also stop using shell=True and all. 并且也停止使用shell=True和全部。 Use real pipes and command lines with arguments (note: this has been tested & works on windows using a native grep command, so now this is portable) 使用带有参数的真实管道和命令行(注意:这已通过本机grep命令进行了测试,并且可以在Windows上使用,因此现在可移植)

#!/usr/bin/env python3
import subprocess

p = subprocess.Popen(['grep','foo'],stdin = subprocess.PIPE)
p.stdin.write(b"fooline\n")
p.stdin.close()
p.wait()

The inconsistency that you observe is due to the fact that shell=True gives you a sh shell, not bash . 您观察到的不一致是由于shell=True给您一个sh shell而不是bash的事实。

The following is valid in bash but not in sh . 以下内容在bash有效,但在sh无效。

grep foo <(echo "fooline")

Example output: 输出示例:

sh-3.2$ grep foo <(echo "fooline")
sh: syntax error near unexpected token `('

If you use a valid sh expression your approach will work. 如果使用有效的sh表达式,则您的方法将起作用。 Alternatively you can specify which shell to use with executable='/bin/bash' . 另外,您可以指定使用哪个shell executable='/bin/bash' You can also use something like: 您还可以使用类似:

subprocess.Popen(['/bin/bash', '-c', cmd])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM