Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
表达式awk、python中的字符无效_Python_Bash_Awk_Subprocess - Fatal编程技术网

表达式awk、python中的字符无效

表达式awk、python中的字符无效,python,bash,awk,subprocess,Python,Bash,Awk,Subprocess,我有一个命令,如下所示: ps v -p 2585 | awk '{if ($9 != "%MEM") {print $9}}' 现在,它在bash中运行良好,只需获取给定pid的内存部分。然而,我现在正试图用python实现它,但我遇到了一些问题。下面是我在python中的内容 cmd1 = ['ps', 'v', '-p', pid] cmd2 = ['awk', '\'{if ($9 != "%MEM") {print $9}}\''] 现在来运行它们 runcmd1 = subpro

我有一个命令,如下所示:

ps v -p 2585 | awk '{if ($9 != "%MEM") {print $9}}'
现在,它在bash中运行良好,只需获取给定pid的内存部分。然而,我现在正试图用python实现它,但我遇到了一些问题。下面是我在python中的内容

cmd1 = ['ps', 'v', '-p', pid]
cmd2 = ['awk', '\'{if ($9 != "%MEM") {print $9}}\'']
现在来运行它们

runcmd1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE)
runcmd2 = subprocess.Popen(cmd2, stdin=runcmd1.stdout, stdout=subprocess.PIPE)
我得到这个错误:

awk: '{if (\$9 != "%MEM") {print \$9}}'
awk: ^ invalid char ''' in expression
我用这个打印出命令的外观。。。 sys.stdout.write('.join(cmd1)+'+'.'+'++'.join(cmd2)+'\n')

它给出了:

ps v -p 1073 | awk '{if ($9 != "%MEM") {print $9}}'

我认为这与实际运行的bash命令没有区别。有人能帮忙吗?

在bash中运行命令时,bash会删除单引号,并为awk提供第一个参数:

{if ($9 != "%MEM") {print $9}} {if($9!=%MEM){print$9} 你给它单引号,你不应该这样做。你应该写:

cmd2 = ['awk', '{if ($9 != "%MEM") {print $9}}'] cmd2=['awk','{if($9!=%MEM”){print$9}}']
当您通过popen运行shell时,不需要保护awk命令不受shell的影响(参数已经被拆分为一个列表,所以您的空格就不用管了)

会很好的


备查 Python有一些很好的编写字符串的方法,可以避免像您在这里尝试的那样,在您确实需要它的情况下进行转义:

'''In this string, I don't need to escape a single ' character,
   or even a new-line, because the string only ends
   when it gets three ' characters in a row like this:'''

"""The same is true of double-quotes like this.
Of course, whitespace and both the ' and " quote characters
are safe in here."""

(我不能保证源代码修饰器在这里能正确显示)

不过,为什么不用一些Python逻辑替换awk逻辑呢。
'''In this string, I don't need to escape a single ' character,
   or even a new-line, because the string only ends
   when it gets three ' characters in a row like this:'''

"""The same is true of double-quotes like this.
Of course, whitespace and both the ' and " quote characters
are safe in here."""