簡體   English   中英

在Java中使用Jython獲取Python參數

[英]Get Python arguments using Jython in Java

我正在嘗試解析python腳本以獲取函數名稱及其參數,我需要使用java來完成。

我設法使用Jython來獲取他們的名字,但是我找不到任何方法來獲取他們的參數(名字,數量?)。

Python示例:

def multiply_by_two(number):
    """Returns the given number multiplied by two

    The result is always a floating point number.
    This keyword fails if the given `number` cannot be converted to number.
    """
    return float(number) * 2

def numbers_should_be_equal(first, second):
    print '*DEBUG* Got arguments %s and %s' % (first, second)
    if float(first) != float(second):

Java代碼:

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile(file.getAbsolutePath());
PyStringMap map=(PyStringMap)interpreter.getLocals();
for (Object key : map.keys()) {
    Object o=map.get(Py.java2py(key));                          
    if (o instanceof PyFunction) {
        System.out.println((String)key); // the function name
        PyFunction function = (PyFunction) o; 
    }
}

我開始對找到一種實現方法的希望失去了...

如果有人有想法,即使不使用Jython

謝謝

函數的內部__code__字典屬性具有函數變量名的co_varnames元組屬性,例如:

def t(t1, t2): pass
t.__code__.co_nlocals

>>>  ('t1', 't2')

關鍵字參數還帶有默認值t.__defaults__ defaults__。

由於__code__是內部實現,因此它在各個解釋器之間可能會發生變化。 AFAIK,它是Python 2.6+以來規范的一部分。

我用了mata答案

是否可以在Python中使用inspect.getargspec()做一個選擇,例如在execfile之后執行類似的操作

 interpreter.exec("import inspect"); PyStringMap map=(PyStringMap)interpreter.eval("dict([(k, inspect.getargspec(v)) for (k, v) in locals().items() if inspect.isfunction(v)]) ") 

這是工作代碼:

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile(file.getAbsolutePath());
interpreter.exec("import inspect"); 
PyDictionary dico=(PyDictionary) interpreter.eval("dict([(k, inspect.getargspec(v).args) for (k, v) in locals().items() if inspect.isfunction(v)])"); 
ConcurrentMap<PyObject, PyObject> map= dico.getMap();
map.forEach((k,v)->{
    System.out.println(k.toString());   
    System.out.println(v.toString());   
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM