簡體   English   中英

調用以所有args作為字符串的Python函數

[英]Python function called with all args given as a string

我正在為我編寫的Python模塊構建一個遠程API。 該代碼將采用通過UDP從Matlab檢索的原始字符串,對其進行解析,然后通過這些字符串對API進行調用。 實際上,我想使用Python語法在Matlab端與我的API接口。

說我有一個功能:

 commands = {'foo':foo}
 def foo(arg1=default, arg2=default):
     ...
     return bar

在Matlab中,我通過UDP發送此消息:

'foo(arg1='in1', arg2='in2')'

在Python服務器端,我有一個字典,函數名作為鍵,相應的函數本身作為值。 我可以調用不帶參數的簡單函數,也可以調用簡單的args,但是在更復雜的東西上我無法使用它。

所以,我有函數,我將args作為字符串, 如何以最直接的方式將args作為此字符串傳遞給函數?

command = commands['foo']
command(argString)

如果可能的話,我想避免使用kwargs。 我已經研究過類似的問題,但還沒有發現任何可行的方法。

編輯這里是一些更具體的代碼; 服務器已經在運行,UDP數據包將在“中斷”中處理,在該中斷中將調用define_command。

發送的matlab數據包是:

cmd = ['get_surrounding_elevation(mode=''coords'',window=3,' ...
'coordinates=Coordinate(36.974117, -122.030796))'];

Python結束:

def func_explode(self, s):
    pattern = r'(\w[\w\d_]*)\((.*)\)$'
    match = re.match(pattern, s)
    if match:
        return list(match.groups())
    else:
        return []

def determine_command(self, command):
    """
    Parse raw input and execute specified function with args
    :param command: The raw command retrieved from UDP
    :return: the command that was executed
    """

    funcArray = self.func_explode(command)
    cmd = self.commands[funcArray[0]]
    args = funcArray[1]

    print cmd(mode='coords', window=3, coordinates=Coordinate(36.974117, -122.030796)) #this works
    try:
        cmd(eval(args))  #this, and other permutations of, doesn't work
        print cmd
    except:
        print "Command Not Found"

    return cmd

嘗試這個:

def foo(*args):
    for a in args:
         print a

#main for test
# call as foo (a1, a2) etc

foo(1, 2, 3)
foo("abc", 1)

輸出:

1個

2

3

abc

1個

暫無
暫無

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

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