-1

I am doing some practice Python exercises and I found one which is asking to create a Python module with various functions. I created a Python package and implemented the functions. So far so good, but a request is that if you call the module with the argument "-h", the message "Help" will be displayed, if the module is being imported, nothing is being displayed. How can we do this, is there any default function that needs to be overwritten? I'm not sure on how can we call a module, I thought we just use a package to better encapsulate our methods

Many thanks and sorry for being noob

  • 2
    If you included the code of what you have tried so far would be much easier to help. – Isma Nov 18 '18 at 19:22

2 Answers2

2

Python is an interpreted language, that just starts with the top-level source code no main function, you might have seen in other languages. Files to be imported are written exactly the same way. All of the code, that is outside of functions is executed.

e.g.
myscript.py

def fn(a, b):
  return a+b

print(fn(1, 1))

This as a fully working program, printing out the answer to, how much is 1+1. But what if you would like to import it to use the fn function inside another script? Doing import myscript would print 2 (and then finally provide you the fn function). The workaround is checking for __name__ == '__main__': inside myscript.py, which will evaluate to true, when being executed only (e.g. python myscript.py). It will be false otherwise (import myscript).

See the related Q&A.

Vojtech Kane
  • 559
  • 6
  • 21
0

Reference: https://docs.python.org/2/howto/argparse.html

$ cat sample.py

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--foo", help="sample argument", action="store", dest='foo')

args = parser.parse_args()
if args.foo:
  print("foo = {}".format(args.foo))

$ python sample.py --help

$ python sample.py --help
usage: sample.py [-h] [--foo FOO]

optional arguments:
  -h, --help  show this help message and exit
  --foo FOO   sample argument
$

$ python sample.py --foo argument_value

$ python sample.py --foo bar
foo = bar
$ python sample.py --foo=10
foo = 10
$
Sharad
  • 9,282
  • 3
  • 19
  • 36