0

我正在生成传递给python -c这样的命令

'python -c "import '+impMod+'; help('+module+'.'+method+') if \''+method+'\' in dir('+module+') else from '+impMod+' import '+method+' help('+method+')"'

并得到这样的输出:

python -c "import os; help(os.path.pathconf) if 'pathconf' in dir(os.path) else from os import pathconf help(pathconf)"

即使我尝试

python -c "import os; help(os.path.pathconf) if 'pathconf' in dir(os.path) else from os import pathconf; help(pathconf)"

但不知道为什么我得到 SyntaxError: invalid syntax

任何帮助将不胜感激,问候。

4

1 回答 1

2

您正在混淆语句和表达式。语法是一个语句,from .. import ..不能出现在表达式中,但您在表达式中使用它... if ... else ...。此外,您可以在 shell 字符串中使用换行符。

python -c "import os
if 'pathconf' in dir(os.path):
    help(os.path.pathconf)
else:
    from os import pathconf
    help(pathconf)"

要在 Python 中执行此操作,您可能需要使用三引号。

于 2013-10-29T18:20:15.567 回答