简体   繁体   English

如何从Python执行多个bash命令?

[英]How to execute multiple bash commands from Python?

I have a grep query: 我有一个grep查询:

grep  "8=ABC\.4\.[24].*\|10=[0-9]+" output.txt |grep "35=8"| cut -d "|" -f 12 >redirect.txt

How do I execute the same from inside a python script? 如何在python脚本中执行相同的操作? I know for a simple grep it works as follows: 我知道对于一个简单的grep,它的工作方式如下:

sed_process = subprocess.Popen(['sed', sed_query,fopen], stdout=subprocess.PIPE) 
grep_query = "8=ABC\.4\.[24].*\|10=[0-9]+"
grep_process = subprocess.Popen(['grep', grep_query], stdin=sed_process.stdout, stdout=subprocess.PIPE)

I'm confused as to how to combine 2 grep commands and a cut command and redirect it to an output file? 我对如何结合使用2个grep命令和cut命令并将其重定向到输出文件感到困惑?

As addressed in the comments, this could all be implemented in python without calling anything. 如评论中所述,所有这些都可以在python中实现而无需调用任何东西。 But if you want to make external calls, just keep chaining like you did in your example. 但是,如果要拨打外部电话,只需像在示例中那样保持链接即可。 The final stdout is an open file to finish off with the redirection. 最终的标准输出是打开的文件,以完成重定向。 Notice I also close parent side stdout so that it doesn't keep an extra entry point to the pipe. 请注意,我还关闭了父侧stdout,以便它不会为管道保留额外的入口点。

import subprocess as subp

p1 = subp.Popen(["grep", "8=ABC\.4\.[24].*\|10=[0-9]+", "output.txt"],
    stdout=subp.PIPE)
p1.stdout.close()
p2 = subp.Popen(["grep", "35=8"], stdin=p1.stdout, stdout=subp.PIPE)
p2.stdout.close()
p3 = subp.Popen(["cut", "-d", "|", "-f", "12"], stdin=p2.stdout, 
    stdout=open('redirect.txt', 'wb'))
p3.wait()
p2.wait()
p1.wait()

For cut it's exactly the same as for grep . 对于cut ,与grep完全相同。 To redirect to a file at the end, simply open() a file and pass that as stdout when running the cut command. 要最后重定向到文件,只需open()文件并在运行cut命令时将其作为stdout传递即可。

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

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