2016-01-13 59 views
3

我在another stack overflow question上找到了關於如何從命令行的python文件中調用特定函數def的答案,但是函數名爲doesn' t拍攝任何參數:運行一個從powershell顯式接收參數的python函數(不需要單獨傳遞參數)

$ python -c 'from foo import hello; print hello()' 

(我扯下了print語句,因爲它似乎是多餘的滿足我的需求,並打電話只是在這種情況下,功能)

幾個答案說使用參數解析,但會需要對已存在的幾個文件進行更改,這是不可取的。

對這個問題的最終答案呈現怎樣做我想做在bash(我需要知道如何做到這一點在PowerShell中)

$ ip='"hi"' ; fun_name='call_from_terminal' 
$ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})" 
hi 

這裏是我的Python代碼

def operator (string): 
    print("Operator here, I got your message: ", string) 

從powershell我想叫它做這樣的事情:

$ python -c 'from myfile import operator; operator("my message here")' 

編輯:

字面命令我打字到PowerShell中

python -c 'from testscript import operator; operator("test")' 

字面錯誤消息,我又回到

Traceback (most recent call last): 
    File "<string>", line 1, in <module> 
NameError: name 'test' is not defined 
+0

你有什麼試過?使用命令行參數運行可執行文件時,PowerShell沒有問題。 –

+0

@Bill_Stewart所有的powershell在這裏都在調用python解釋器。我很抱歉,我做了一個糟糕的工作,說我不想把這個參數作爲額外的參數(比如通常在CLI上的參數)傳遞給python文件,然後必須做一些額外的工作來獲取參數並調用該函數。我想從命令行中調用,就像在Python中一樣,參數直接傳遞給函數,而不是作爲python的參數。我主要提到與變量相關的任何語法問題。 – Tuffwer

+0

「參數直接傳遞給函數而不是作爲python的參數」 - 你能解釋一下你的意思嗎?你在python命令行中指定的任何東西都是「python的參數」。 –

回答

3

我想我明白這個問題。即使您指定單引號(它試圖有幫助),PowerShell也會將雙引號傳遞給可執行文件。使用showargs.exe(見http://windowsitpro.com/powershell/running-executables-powershell):

PS C:\> showargs python -c 'from testscript import operator; operator("test")' 
python -c "from testscript import operator; operator("test")" 

您應該能夠逃脫你的字符串中的字符"傳遞給Python解釋器,無論是這樣的:

PS C:\> showargs python -c "from testscript import operator; operator(\""test\"")" 
python -c "from testscript import operator; operator(\"test\")" 

或者是這樣的:

PS C:\> showargs python -c "from testscript import operator; operator(\`"test\`")" 
python -c "from testscript import operator; operator(\"test\")" 
相關問題