0

I have a file hello.py and multiple methods inside. My file looks like:

def method1():
    return data

def method2(args):
    return args

if __name__ == '__main__':
    method1()
    method2(args)

If I run hello.py, all methods run. But, how can I run these methods separately for example ?

Nerd
  • 265
  • 6
  • 18

2 Answers2

0

So from your comments, I think you want this:

def method1(arg):
    print("hello", arg)

def method2(arg):
    print("Whatsup", arg)

if __name__ == "__main__":
    import sys
    #print(sys.argv)
    func = sys.argv[1]
    arg = sys.argv[2]
    if func == "method1": method1(arg)
    elif func == "method2": method2(arg)

Now run this by python3 hello.py method1 John This is a dirty example, if you want more options, you need to tweak a lot.

J Arun Mani
  • 620
  • 3
  • 20
0

From the command line you can, for example, run method1:

$ python -c 'import hello; hello.method1()'

or method2:

$ python -c 'import hello; hello.method2(somearg,someotherarg)'

This requires the command to be ran in the directory where hello.py is, or hello.py to be in PYTHONPATH.

Allowing flexibility, you can tweak the string and run any valid method with any valid argument as needed.

For more information, take a look at this answer on how to run functions from the command line.

Attersson
  • 4,755
  • 1
  • 15
  • 29