[英]How to use Subprocess in Python
我想在 python 中执行以下 shell 命令: grep 'string' file | tail -1 | cut -c 1-3
grep 'string' file | tail -1 | cut -c 1-3
我试过了:
import subprocess
i = 1
while i < 1070:
file = "sorted." + str(i) + ".txt"
string = "2x"
subprocess.call(grep 'string' file | tail -1 | cut -c 1-3)
i = i + 1
任何帮助,将不胜感激。 谢谢。
首先,您传递给subprocess.call
的任何内容都应该是一个字符串。 您的代码中未定义名称grep
、 file
、 tail
和cut
,您需要将整个表达式转换为字符串。 由于 grep 命令的搜索字符串应该是动态的,因此您需要先构造最终字符串,然后再将其作为参数传递给 function。
import subprocess
i = 1
while i < 1070:
file = "sorted." + str(i) + ".txt"
string = "2x"
command_string = 'grep {0} {1} | tail -1 | cut -c 1-3'.format(string, file)
subprocess.call(command_string)
i = i + 1
您可能希望向subprocess.call
传递一个附加参数: shell=True
。 该参数将确保命令通过 shell 执行。
您的命令正在使用cut
。 您可能想要检索子进程的 output,因此更好的选择是创建一个新进程 object 并使用subprocess.communicate
与原来的 output 捕获:
import subprocess
i = 1
while i < 1070:
file = "sorted." + str(i) + ".txt"
string = "2x"
command_string = 'grep {0} {1} | tail -1 | cut -c 1-3'.format(string, file)
p = subprocess.Popen(command_string, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdoutdata, stderrdata = p.communicate()
# stdoutdata now contains the output of the shell commands and you can use it
# in your program
i = i + 1
编辑:这是有关如何将数据存储到文本文件中的信息,如评论中所要求的。
import subprocess
outputs = []
i = 1
while i < 1070:
file = "sorted." + str(i) + ".txt"
string = "2x"
command_string = 'grep {0} {1} | tail -1 | cut -c 1-3'.format(string, file)
p = subprocess.Popen(command_string, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdoutdata, stderrdata = p.communicate()
# stdoutdata now contains the output of the shell commands and you can use it
# in your program, like writing the output to a file.
outputs.append(stdoutdata)
i = i + 1
with open('output.txt', 'w') as f:
f.write('\n'.join(outputs))
子进程期望 arguments 作为字符串或数组:
subprocess.call("grep '{}' {} | tail -1 | cut -c 1-3".format(string, file), shell=True)
shell=True
是必要的,因为您使用的是特定于 shell 的命令,例如 pipe。
但是,在这种情况下,在纯 python 中实现整个程序可能要容易得多。
请注意,如果字符串或文件包含任何特殊字符(包括空格或引号),则该命令将不起作用,并且实际上可能对您的系统执行各种不需要的操作。 如果您需要它处理的不仅仅是这些简单的值,请考虑使用纯 python 解决方案,设置shell=False
并使用手动管道的数组语法,或某种形式的 escaping。
您的命令应作为字符串提供。 另外,如果你想得到你的命令的output,你可以使用如下:
subprocess.run("grep 'string' file | tail -1 | cut -c 1-3", shell=True, capture_output=True, check=True)
其中capture_output
(适用于 Python3.7+)返回 object 和returncode
, stdout
和stderr
如果您的命令失败, check
标志将引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.