2017-01-24 33 views
0

我使用Python 3.6,我有一個名爲file.py文件,與此有兩個功能:調用帶有參數的functionfrom命令行 - 的Python(多功能選擇)

def country(countryName): 
    print(countryName) 

def capital(capitalName): 
    print(capitalName) 

我需要調用這兩種方法中的任何一種都來自命令行,但我真的不知道該怎麼做,也有這種方式的參數。

python file.py <method> <argument> 

有人知道該怎麼做嗎?

問候!

+0

的可能的複製[調用了一個Python外部命令(http://stackoverflow.com/questions/89228/calling-an-external-command-in-python) –

回答

1

要在程序中使用命令行參數,您可以使用sys.argv。 Read more

import sys 

def country(countryName): 
    print(countryName) 

def capital(capitalName): 
    print(capitalName) 

method_name = sys.argv[1] 
parameter_name = sys.argv[2] 

getattr(sys.modules[__name__], method_name)(parameter_name) 

要運行的程序:

python file.py capital delhi 

輸出:

delhi 

你輸入參數method_name是一個字符串,因此不能直接調用。因此我們需要使用getattr來獲取方法句柄。

命令sys.modules[__name__]獲取當前模塊。這是file.py模塊。然後我們使用getattr來獲取我們想調用的方法並調用它。我們通過參數的方法`(PARAMETER_NAME)」

+0

謝謝辛格太多了! :) –

0

,你可以有檢查您的file.py模塊,executor.py調用它,並在file.py處理參數列表調整你的方法

executor.py:

import file 
import sys  

method = file.__dict__.get(sys.argv[0]) 
method(sys.argv[1:-1])