2013-10-29 25 views
0

我生成傳遞給python -c命令這樣通過串聯

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

建立一個Python的命令,並得到輸出是這樣的:

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:無效的語法

任何幫助將不勝感激, 關心。

+0

你不需要'';'' – jramirez

+1

好吧不是這樣的話,請進一步檢查這一行,我猜它是什麼時候在介紹help後面的'from'進口pathconf' –

+0

是的,python沒有使用這些。 – jramirez

回答

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中這樣做,您可能需要使用三重引號。

+2

哦,在你的情況下,如果第一個if塊爲真,則help()將執行兩次。 –

+0

@san - 變了,謝謝。 –

+0

讓它工作。 –