【发布时间】:2020-04-21 13:24:48
【问题描述】:
我有一个检查文件是否存在的函数,它返回'True'/'False',现在我正在用eval()将它“转换”为布尔值,但我认为这不是最聪明的解决方案,但我不确定如果没有不必要的ifs,我该怎么做,
>>> foo = 'False'
>>> type(eval(foo))
<class 'bool'>
>>> type(foo)
<class 'str'>
例如,我在 ssh 连接的机器上运行这个表达式
"test -e {0} && echo True || echo False".format(self.repo)
这样,我的结果将是字符串。
def execute(command):
(_, stdOut, _) = ssh.exec_command(command)
output = stdOut.read()
return output.decode('utf-8')
还有其他方法可以实现吗?
【问题讨论】:
-
shell 行没有理由回显任何内容。如果表达式为真,
test -e {0}的 退出状态 将为 0,否则为非零(可能为 1)。测试那个。 -
不,
ssh的退出状态将是它运行的命令的退出状态。无论您使用什么来运行ssh,都将提供某种方式来访问整数退出状态。 (例如,subprocess.run(['ssh', some_host, f'test -e "{some_file}"']).returncode == 0(忽略确保some_file正确转义以包含在 shell 命令中的问题。)