0

I'm using Python 3.6, I have a file called file.py, with have this two functions:

def country(countryName):
    print(countryName)

def capital(capitalName):
    print(capitalName)

I need to call any of these two methods from Command Line, but sincerely I don't know how to do that, also with arguments in this way.

python file.py <method> <argument>

Does someone knows how to do that?

Greetings!

2 Answers2

3

To use command line arguments in a program you can use 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)

To run the program:

python file.py capital delhi

output:

delhi

Your input parameter method_name is a string so can't be called directly. Hence we need to fetch the method handle using getattr.

Command sys.modules[__name__] fetches the current module. which is file.py module. Then we use getattr to fetch the method we want to call and call it. we pass the parameter to the method as `(parameter_name)'

Vikash Singh
  • 13,213
  • 8
  • 40
  • 70
0

you could have a module that inspects your file.py, call it executor.py, and adjust your methods in file.py to handle argument lists

executor.py:

import file
import sys    

method = file.__dict__.get(sys.argv[0])
method(sys.argv[1:-1]) 
bwooceli
  • 371
  • 1
  • 2
  • 11