0

Let's say I have two modules:

  • a.py:

    import argparse
    
    
    parser = argparse.ArgumentParser()
    parser.add_argument("arg", help="Some argument")
    args = parser.parse_args()
    
    
    def func():
        print('Hello world!')
    
  • b.py:

    from a import func
    
    func()
    

When I execute python3.8 '/home/b.py'

I got

usage: b.py [-h] arg
b.py: error: the following arguments are required: arg

...even though func doesn't need to use system arguments to be executed

Is there any way I can import and execute func without passing system arguments to b.py?

JaSON
  • 4,843
  • 2
  • 8
  • 15

1 Answers1

3

You are causing script a.py to run at import time from script b.py. You just need to change it to:

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("arg", help="Some argument")
    args = parser.parse_args()


def func():
    print('Hello world!')

Why this works is explained very well here so I won't rehash it! What does if __name__ == "__main__": do?

regoawt
  • 106
  • 1
  • 2