Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run multiple lines using python -c

Tags:

python

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?

like image 361
mario.hsu Avatar asked Jan 14 '23 09:01

mario.hsu


1 Answers

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.

like image 146
icktoofay Avatar answered Jan 22 '23 12:01

icktoofay