在os.system()中匹配引号

问题描述 投票:1回答:1
os.system('''awk \'$1 == "RULE" && $8 !=0{print $2, $8}\' "{}/ABC*XYZ*" | sort -u >>error_file'''.format(path))

sort -u >>error_file'''.format(path)) On executing this command using terminal the command works fine but using os....

KeyError: 'print $2, $8'

You should understand what does
python unix quotes
1个回答
0
投票

Now you want to use format to fill a command, but in fact your command has two bracket paris, so it will try to fill all of them --- explicit, it will failed.formatYou should write '{{print $2, $8}}' if you just want to use a bracket text instead of fill something else. So your code should be:

'a{}c'.format('b')
>>> abc
'a{b}c'format(b='b')
>>> abc

I don't know more about

, so I'm not sure it can be work as what you want, but at least I'm pretty sure you don't need reverse slash here. It equals to

And, an interesting point, I think you don't need, but just show here:

os.system('''awk \'$1 == "RULE" && $8 !=0{{print $2, $8}}\' "{}/ABCXYZ" | sort -u >>error_file'''.format(path))

Though you can't use awk as a param name, but in fact you can pass it as a dict key:)

os.system('''awk '$1 == "RULE" && $8 !=0{{print $2, $8}}' "{}/ABCXYZ" | sort -u >>error_file'''.format(path))

os.system('''awk '$1 == "RULE" && $8 !=0{print $2, $8}' "{}/ABCXYZ" | sort -u >>error_file'''.format(path, **{'print $2, $8': '{print $2, $8}'}))

print $2, $8os.system('''awk '$1 == "RULE" && $8 !=0{print $2, $8}' /\ "{}ABCXYZ"

© www.soinside.com 2019 - 2024. All rights reserved.