我需要执行
grep 'ERROR:A:\|ERROR:B:\|ERROR:C:\|RESOLVED:A:\|RESOLVED:B:\|RESOLVED:C:' /HOME/SOME_LOCATION/FILENAME
这在shell中运行良好,但我需要从我的python脚本中执行它。 所以在python脚本中我做
filename = "/HOME/SOME_LOCATION/FILENAME"
cmd = 'grep \'ERROR:A:\|ERROR:B:\|ERROR:C:\|RESOLVED:A:\|RESOLVED:B:\|RESOLVED:C:\' '+filename+''
但如果我把它交给
commands.getstatusoutput(cmd)
它给出了错误
commands.getstatusoutput(cmd)
File "<stdin>", line 1
commands.getstatusoutput(cmd)
^
IndentationError: unexpected indent
我试图找到cmd有什么,奇怪的是它是
>"grep 'ERROR:A:\\|ERROR:B:\\|ERROR:C:\\|RESOLVED:A:\\|RESOLVED:B:\\|RESOLVED:C: /HOME/SOME_LOCATION/FILENAME"
有没有办法让这个命令工作。
这只是我更大目标的一部分,我还需要使用grep -c来获取匹配字符串的计数,用之前的grep计数检查它(我会保存在某个变量中)并使用差异,打印最后这样的台词。例如。如果grep -c'exp'文件给出15并且前一个计数为10(意味着已经添加了5个新条目),我需要打印那些5.但是我现在已经卡在了开头。
Python 2.5
答案 0 :(得分:0)
关于单引号。
\'ERROR
前面的逃脱单引号正在创造我认为的问题
将其更改为双引号,它将起作用:
>>> import commands
>>> filename = '/home/rituraj/codetosuccess.txt'
>>> cmd = 'grep \"ERROR:A:\\|ERROR:B:\\|ERROR:C:\\|RESOLVED:A:\\|RESOLVED:B:\\|RESOLVED:C:\" '+filename
>>> commands.getstatusoutput(cmd)
(0, 'ERROR:A:\\|ERROR:B:\\|ERROR:C:\\|RESOLVED:A:\\|RESOLVED:B:\\|RESOLVED:C:')
答案 1 :(得分:0)
我用过
cmd = """grep \'ERROR:A:\|ERROR:B:\|ERROR:C:\|RESOLVED:A:\|RESOLVED:B:\|RESOLVED:C:\''+filename+''
然后会显示
>>>cmd
"grep 'ERROR:negativeSpread:\\|ERROR:mktdataLimit:\\|ERROR:instNoData:\\|RESOLVED:negativeSpread:\\|RESOLVED:mktdataLimit:\\|RESOLVED:instNoData:' /home/trading/chaya/logs/today/20140730.latency.log"
>>> print cmd
grep 'ERROR:negativeSpread:\|ERROR:mktdataLimit:\|ERROR:instNoData:\|RESOLVED:negativeSpread:\|RESOLVED:mktdataLimit:\|RESOLVED:instNoData:' /home/trading/chaya/logs/today/20140730.latency.log
>>> commands.getstatusoutput(cmd1)
绝对正常。
所以这仍然有点用词不当,我从stackoverflow上的帖子中得到了这个理解(不能发布链接,因为我需要15个声誉)
全部谢谢