4

I need to use python -c to remotely run some code, it works when I use:

python -c "a=4;print a"
4

Or

python -c "if True:print 'ye'"

But python -c "a=4;if a<5:print 'ye'" will generate an error:

File "<string>", line 1
    a=4;if a<5:print 'ye'
    SyntaxError: invalid syntax

What should I do to make it work, any advice?

1 Answer 1

9

Enclose it in single quotes and use multiple lines:

python -c '
a = 4
if a < 5:
    print "ye"
'

If you need a single quote in the code, use this horrible construct:

python -c '
a = 4
if a < 5:
    print '\''ye'\''
'

This works because most UNIX shells will not interpret anything between single quotes—so we have some Python code right up until where we need a single quote. Since it’s completely uninterpreted, we can’t just escape the quote; rather, we end the quotation, then insert a literal quotation mark (escaped, so it won’t be interpreted as the start of a new quote), and finally another quote to put us back into the uninterpreted-string state. It’s a little ugly, but it works.

Sign up to request clarification or add additional context in comments.

7 Comments

Also note that this isn't specific for Python or python -c in any way, and will work for git commit -m and lots of other commands aswell.
thanks for this quick answer,but I'm using a tool which doesn't accept line change (Enter key), that means I have to use command formed [python -c 'line1;line2;line3......' ], do you have solution for this ?
@mario.hsu: You can use this even more horrible construct: python -c 'a = 4'$'\n''if a < 5:'$'\n'' print "ye"'
horrible but useful ,thanks ,but it needs to be changed a little bit python -c 'a = 4'$'\n''if a < 5:'$'\n\t'' print "ye"'
@mario.hsu: I actually had four spaces indenting the print but Stack Overflow collapsed it into one space. Pretend that there were four spaces there and it should work.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.