0

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()"

5
  • Can you make one function per file? Commented May 6, 2020 at 3:31
  • @MVB76 And then just import them seperately, making sure they are all in the same directory Commented May 6, 2020 at 3:33
  • duplicate? stackoverflow.com/questions/3987041/… Commented May 6, 2020 at 3:33
  • why not use eval? Commented May 6, 2020 at 3:46
  • @ impopularGuy can you give me detail info on eval function. how can execute this command python3 File.py test1() test2() test3() using eval Commented May 6, 2020 at 5:48

2 Answers 2

1

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().

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

I am getting an error saying that File "main.py", line 13, in main locals()["function_name"]() TypeError: 'str' object is not callable
My bad, sorry. Please remove the quotes around function_name, see fixed code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.