Search code examples
pythoncommand-line-interfaceargs

How to take arguments in python 3 like myscript.py -i input.txt?


I want my script to take args like:

python myscript.py -i input.fastq -q 23 -l 30 -o outfile.fastq

not like

python myscript.py input.fastq 23 30 outfile.fastq

Is there any package available to do this in python?


Solution

  • You can use argparse for this:

    For example python myscript.py -s customscriptvalue

        import argparse
    
       # Parse arguments
        parser = argparse.ArgumentParser(description='Script options')  
        parser.add_argument('-s', '--script', help='Custom Script to execute', default=None)
        result = parser.parse_args()
    
        # Treat Arguments in your script
        arguments = dict(result._get_kwargs())
        if arguments['script'] is not None:
            scriptMode = True
            scriptPath = arguments['script']
    

    See https://docs.python.org/3/library/argparse.html