简体   繁体   中英

How to Python print a line from a config file containing semi-colons?

I have a python 2.7 script on Ubuntu 12.04, using Fabric local commands it gets from a text file. When I try to use a one-liner with semi-colons in it, Fabric fails to parse the line and breaks. Is there a syntax that works, or should I look elsewhere to run this command?

--------- edit -----------

a more concise problem statement than the actual one originally included. It is not about Fabric at all, even print won't work with this text in a config file:

a python config file:

[firmware-jobs] 1: echo ".... ; ....." > /tmp/tmp-file

a python file with Fabric:

from ConfigParser import SafeConfigParser confparser = SafeConfigParser() confparser.read(CONFFILE)

for (key, command) in CONFOBJ.items('firmware-jobs'): try: print command

------ end edit -----------

if grep -q "CPLD " tmp-file ; then echo "y" | <some long command> ; fi

I have tried:

"if grep -q "CPLD " tmp-file ; then echo "y" | <some long command> ; fi"
if grep -q "CPLD " tmp-file '\;' then echo "y" | <some long command> '\;' fi
if grep -q "CPLD " tmp-file ";" then echo "y" | <some long command> ";" fi

typical failure:

[localhost] local: "if grep -q "CPLD " tmp-file
/bin/sh: 1: Syntax error: Unterminated quoted string

Fatal error: local() encountered an error (return code 2) while executing '"if grep -q "CPLD " tmp-file'

requirements:

I do not wish to move the conditional into Python, because the text file supports a generic Python script across different hardware platforms and releases.

You need to use different quotes outside and inside the string, otherwise Python thinks you're ending the string. Try this:

'if grep -q "CPLD " tmp-file ; then echo "y" | <some long command> ; fi'

Or if you also need to use single quotes inside the string, this:

'''if grep -q "CPLD " tmp-file ; then echo "y" | <some long command> ; fi'''

Python considers triple-quotes to be a distinct kind of quote from single quotes, and doesn't end the string until it sees another triple quote. (This also works with """ .)

its a bug in 2.7 configparser

http://bugs.python.org/issue16374

semicolons are inline comment delimiters

Thanks for the suggestions!

It sounds like the problem is quotes on the outside of the string in the command you would like to get rid of. The strip string method would do that for you:

command = command.strip(" '")

Also, stick with Amber's answer on how to format the command as a whole, it looks correct to me.

Finally, try running the command directly in the shell, if it works fine there, that should be the format fed to Fabric.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM