sathis
sathis

Reputation: 115

python - adding a argument to execution script

consider I am having a following code in my bin as follows(filename: emp_dsb):

import sys

from employee_detail_collector.EmpCollector import main

if __name__ == '__main__':
    sys.exit(main())

In my command line I will execute the "emp_dsb", so that above code will execute the main function from "employee_detail_collector.EmpCollector"

Code in (employee_detail_collector.EmpCollector) main():

def main():
    try:
        path = const.CONFIG_FILE
        empdsb = EmpDashboard(path)
    except SONKPIExceptions as e:
        logger.error(e.message)
    except Exception as e:
        logger.error(e)

Now I need to add some argument here for emp_dsb, that is like "emp_dsb create_emp" should invoke a new set of functionalities for creating a employee, which is also needs to be added in same main()

someone look and let me know your ideas, If not clear let me know so that i will try to make it more clear.

Upvotes: 0

Views: 97

Answers (2)

Shobeir
Shobeir

Reputation: 127

I would personally use 'argparse' module. Here is the link to a dead simple code sample.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print(args.echo)

Upvotes: 1

hiro protagonist
hiro protagonist

Reputation: 46849

the standard way to use command line arguments is to do this:

import sys

if __name__ == '__main__':

    print(sys.argv)

read up on the doc of sys.argv.

then there are fancier ways like the built-in argparse and the 3rd party docopt or click.

Upvotes: 1

Related Questions