2011-06-24 32 views
4

我在Java中使用Jython;所以我有一個Java設置類似如下:Jython 2.5.1:從Java調用到__main__ - 如何傳遞命令行參數?

String scriptname="com/blah/myscript.py" 
PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState()); 
InputStream is = this.getClass().getClassLoader().getResourceAsStream(scriptname); 
interpreter.execfile(is); 

,這將(例如)運行下面的腳本:

# myscript.py: 
import sys 

if __name__=="__main__": 
    print "hello" 
    print sys.argv 

如何通過使用這種方法「命令行」的論點? (我希望能夠編寫我的Jython腳本,以便我也可以在命令行上使用'python腳本arg1 arg2'來運行它們)。

回答

9

我使用Jython 2.5.2和runScript不存在,所以我不得不用execfile來替換它。除此之外差,我還需要創建PythonInterpreter對象之前設置argv中的狀態對象:

String scriptname = "myscript.py"; 

PySystemState state = new PySystemState(); 
state.argv.append (new PyString ("arg1")); 
state.argv.append (new PyString ("arg2")); 

PythonInterpreter interpreter = new PythonInterpreter(null, state); 
InputStream is = Tester.class.getClassLoader().getResourceAsStream(scriptname); 
interpreter.execfile (is); 

argv列表中的狀態對象最初具有1的長度,以在它的一個空字符串,所以前面的代碼導致輸出:

hello 
['', 'arg1', 'arg2'] 

如果您需要argv[0]是實際的腳本名稱,你需要創建這樣的狀態:

PySystemState state = new PySystemState(); 
state.argv.clear(); 
state.argv.append (new PyString (scriptname));  
state.argv.append (new PyString ("arg1")); 
state.argv.append (new PyString ("arg2")); 

然後輸出爲:

hello 
['myscript.py', 'arg1', 'arg2'] 
+0

好的一個 - 我只需要檢查了這一點與我的Jython的版本(2.5.1實際..不是2.5道歉);我會盡快將其標記爲已接受。乾杯 – monojohnny

+0

另外:'runScript'是我的方法 - 我已經在我的代碼中包裝類 - 我已更正原始帖子使用'execfile' – monojohnny

+0

是的,作品一種享受;注意到似乎有一個記錄方法來檢索systemState,但似乎沒有在我的發行版上:http://www.jython.org/javadoc/org/python/util/PythonInterpreter.html#getSystemState%28 %29 - 感謝接受答案。 – monojohnny

0

對於那些誰上述解決方案不工作的人,試試下面的。這適用於我在jython上的版本2.7.0

String[] params = {"get_AD_accounts.py","-server", "http://xxxxx:8080","-verbose", "-logLevel", "CRITICAL"}; 

上面重複了以下命令。即每個參數及其值是params數組中的單獨元素。

Jython的get_AD_accounts.py -loglevel關鍵-server http://xxxxxx:8080 -verbose

PythonInterpreter.initialize(System.getProperties(), System.getProperties(), params); 

PySystemState state = new PySystemState() ; 

InputStream is = new FileInputStream("C:\\projectfolder\\get_AD_accounts.py"); 
      PythonInterpreter interp = new PythonInterpreter(null, state); 

PythonInterpreter interp = new PythonInterpreter(null, state); 
interp.execfile(is);