我正在尝试通过python subprocess
运行此命令cat /etc/passwd | awk -F':' '{print $1}'
我所做的是通过运行两个子进程运行命令。
1st:哪个会获取结果,即。 cat / etc / passwd
第二:第一个的输出将作为输入提供给第二个 awk -F':' ' {print $ 1}'
以下是代码:
def executeCommand(self, command, filtercommand):
cmdout = subp.Popen(command, stdout=subp.PIPE)
filtered = subp.Popen(filtercommand, stdin=cmdout.stdout, stdout=subp.PIPE)
output, err = filtered.communicate()
if filtered.returncode is 0:
logging.info("Result success,status code %d", filtered.returncode)
return output
else:
logging.exception("ErrorCode:%d %s", filtered.returncode, output)
return False
其中,
command = [' sudo',' cat',' / etc / shadow']
filtercommand = [' awk'," -F':'","' {print $ 1}'",' |',' uniq']
错误:
awk: 1: unexpected character ''' error
我如何创建传递给函数的filercommand列表:
filtercommand=["awk","-F\':\'", "\'{print $1}\'", '|', 'uniq']
答案 0 :(得分:0)
您可以直接使用subprocess.Popen
使用管道命令,并获取输出和错误:
import subprocess
cmd = "cat /etc/passwd | awk -F':' 'NF>2 {print $1}'"
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output, err = p.communicate()
print output
print err
但是请注意cat
在上面的管道命令中完全没用,因为awk
可以直接对文件进行操作,如下所示:
cmd = "awk -F':' 'NF>2 {print $1}' /etc/passwd"