2014-02-20 29 views
0

我希望能夠通過json編碼和解碼一個方法,參數對。類似這樣的:如何從json編碼對象重建命令

fn = 'simple_function' 
arg = 'blob' 

encoded = json.dumps([fn, arg]) 
decoded = json.loads(encoded) 

method, args = decoded 
fn = getattr(self, method) 
fn(*args) 

但它失敗,因爲python將'blob'字符串分裂成每個字符(奇怪的行爲)的元組。如果參數是一個實際的項目列表,我想它是有效的。它也失敗,如果我們不想發送任何參數,調用一個沒有參數的函數(沒有足夠的值來解壓錯誤。)

如何構造一個非常普遍的機制?我試圖製作一個可以通過這種方式調用客戶端上的函數的服務器,主要是因爲我不知道該怎麼做。

所以,尋找一種解決方案,讓我可以調用沒有,一個或任意數量的參數的函數。

理想的解決方案可能是這個樣子:

def create_call(*args): 
    cmd = json.dumps(args) 

def load_call(cmd): 
    method, optional_args = json.loads(*cmd) 
    fn = getattr(object, method) 
    fn(*optional_args) 

,將與無參數工作,一個單個String參數不得到由*在分頭列表,或任何一個列表種類的參數。

回答

0

您的參數是一個單一的對象。不是一個列表。所以,你需要或者

fn = 'simple_function' 
arg = 'blob' 

encoded = json.dumps([fn, arg]) 
decoded = json.loads(encoded) 

method, args = decoded 
fn = getattr(self, method) 
fn(args) #don't try to expand the args 

OR

fn = 'simple_function' 
arg = 'blob' 

encoded = json.dumps([fn, [arg]]) #make sure to make a list of the arguments 
decoded = json.loads(encoded) 

method, args = decoded 
fn = getattr(self, method) 
fn(*args) 

OR

fn = 'simple_function' 
arg = 'blob' 

encoded = json.dumps([fn, arg]) 
decoded = json.loads(encoded) 

method, args = decoded[0], decoded[1:] #cut them up into a single function name and list of args 
fn = getattr(self, method) 
fn(*args) 

其中 「或」 真的取決於你想要什麼。

+0

但是,如果我有一個沒有參數的函數,那麼這會傳遞一個空列表。 –

+0

@ user11177添加了一個應該支持該功能的附加變體。 –