简体   繁体   English

如何使用python -c运行多行

[英]How to run multiple lines using python -c

I need to use python -c to remotely run some code, it works when I use: 我需要使用python -c远程运行一些代码,它在我使用时工作:

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: 但是python -c "a=4;if a<5:print 'ye'"将产生错误:

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

What should I do to make it work, any advice? 我该怎么做才能使它有效,有什么建议吗?

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. 这是有效的,因为大多数UNIX shell不会解释单引号之间的任何内容 - 所以我们有一些Python代码,直到我们需要单引号。 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. 这有点难看,但它确实有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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