如何在单行if语句中运行函数

时间:2018-03-29 01:18:54

标签: python python-2.7

我有这个if语句,我试图将其转换为在终端shell中使用的单行,但似乎无法使其工作。

基本上代码类似于:

import module

if condition:
    module.runCustomMethod()
else:
    pass

所以我试着这样写:

import module;module.runCustomeMethod() if condition == True else pass

但无论我如何安排它,它总是给我一个语法错误。我将如何以这种方式运行方法?

1 个答案:

答案 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