chinna
chinna

Reputation: 55

how to call the methods as command arguments in python

I have a sample program like

File.py

def test1():
    print("test1")
def test2():
    print("test2")
def test3():
    print("test3")
def main():
    sys.argv[1]
    sys.argv[2]
    sys.argv[3]
 #   test1()
 #   test2()
 #   test3()

main()

I need to execute a command like "python3 File.py test1() test2() test3()"

some scenarios I need to execute only one or two methods only "python3 File.py test1() test2()"

Upvotes: 0

Views: 34

Answers (2)

Kate Melnykova
Kate Melnykova

Reputation: 1873

I would fill out the main function as follows:

arguments = list(sys.argv)
arguments.pop(0)
while arguments:
    function_name = arguments.pop(0)
    locals()[function_name]()

Then, in command line you type:

$ python3 file.py test1 test3 test2

Upvotes: 1

Athos
Athos

Reputation: 109

I am not sure if this is what you were looking for, but if you open the CMD in the directory your file.py is saved in, you can use:

python -i file.py

This will open the file in the interactive shell. You can then access the functions with a normal function call, like test1().

Upvotes: 1

Related Questions