我有这个if语句,我试图将其转换为在终端shell中使用的单行,但似乎无法使其工作。
基本上代码类似于:
import module
if condition:
module.runCustomMethod()
else:
pass
所以我试着这样写:
import module;module.runCustomeMethod() if condition == True else pass
但无论我如何安排它,它总是给我一个语法错误。我将如何以这种方式运行方法?
答案 0 :(得分:1)
你要做的事情非常难看,有更好的方法可以做到,但......
import module;module.runCustomeMethod() if condition == True else pass
这里的问题是pass
是一个语句,Python表达式永远不能包含语句。
由于您未使用表达式的值,因此您可以将pass
替换为任何无法评估的表达式:
import module;module.runCustomeMethod() if condition == True else None
现在代码中没有SyntaxError
。虽然它仍然不起作用,因为condition
并未在任何地方定义,所以它只会提升NameError
。但是,如果您的实际代码中没有问题,那么这将有效。
作为旁注,您几乎总是只想要if condition
,而不是if condition == True
。只有在您特别想要接受True
并拒绝其他真实值(例如1
)时才使用它。
如果您在sh脚本中执行此操作,最干净的解决方案可能就是:
python <<EOF
import module
if condition:
module.runCustomeMethod()
EOF