如何在单行中使用if/else(python -c)?

mbz*_*slk 5 python python-2.7

我刚刚开始学习python,我试图在python -c中使用if/else语句,但我一直收到Invalid Syntax错误.我想用python -c调用if/else的原因是因为我想在我的bash脚本中用if/else调用一些python模块.是否可能,我想坚持python -c而不是python -m?

以下是我到目前为止所尝试的内容

试试1

python -c "if False: print 'not working';else print 'working'"
  File "<string>", line 1
    if False: print 'not working';else print 'working'
                                     ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

试试2

python -c "if False:    print 'not working';else:    print 'working'"
  File "<string>", line 1
    if False:    print 'not working';else:    print 'working'
                                        ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

Try3

python -c "if False:;    print 'not working';else:;    print 'working'"
  File "<string>", line 1
    if False:;    print 'not working';else:;    print 'working'
             ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

有关如何解决此问题的任何建议?

如果我想使用| elif | elif | else类型的声明怎么办?

提前致谢!

Cha*_*ffy 6

对于真正的通用解决方案 - python -c不仅限于单线.

python -c '
if True:
  print "hello"
else:
  print "world"
'
Run Code Online (Sandbox Code Playgroud)

当然,如果您真的想要,可以将多行字符串格式化为一行:

python -c $'if True:\n\tprint "hello"'\nelse:\n\tprint "world"'
Run Code Online (Sandbox Code Playgroud)

......但是,很显然,这是一个非常糟糕的主意.

如果你真的,真的想在shell中包装Python代码,为什么不使用函数呢?甚至比这更好,为什么不为你的代码使用引用的heredocs?(这样做可以让你保持代码本身的文字,通过argv传递参数).

python_argv_repr() {
  python - "$@" <<'EOF'
import sys
print sys.argv[1:]
EOF
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*dmh 5

简单一点,使用三元形式:

$ python -c "print 'A' if False else 'B'"
Run Code Online (Sandbox Code Playgroud)


Ash*_*ary 3

使用条件表达式和打印函数:

C:\> python -c "from __future__ import print_function; print('not wo
rking') if False else print ('working')"
working
Run Code Online (Sandbox Code Playgroud)