2017-05-31 63 views
-1

我试图通过Python子AWK:1:意外的字符“””错误

cat /etc/passwd | awk -F':' '{print $1}' 

我所做的是通过运行两个子进程运行的命令来运行这个命令。

1st:将取出结果即。 猫/ etc/passwd中

第二:第一的输出将被馈送作为输入提供给第二AWK -F ':' '{打印$ 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 

命令= [ '须藤', '猫', '/ etc/shadow的']

filtercommand = [ 'AWK', “-F ':'”, “ '{打印$ 1}'”,' |”, 'uniq的']

错误:

awk: 1: unexpected character ''' error 

如何创建传递给函数的filercommand列表:

filtercommand=["awk","-F\':\'", "\'{print $1}\'", '|', 'uniq'] 
+0

'''{print $ 1}'“'中不需要单引号。只需删除它们。而且,'“-F”'和'“':'”'必须是两个独立的参数,后者也不需要单引号。 – DyZ

+0

尝试没有单引号抛出'awk:can not open | (没有这样的文件或目录)' –

+1

'''不是命令行参数,它是一个shell重定向。你不能以这种方式使用它。您必须重新连接'awk'的标准输出到'uniq'的标准输出,就像您将'cat'的标准输出重新连接到'awk'的标准输出一样。顺便说一句,你可以做'sudo awk -F':''{print $ 1}'/ etc/shadow',而不用'cat'。 – DyZ

回答

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"