Execute python script using variable from linux shell

This may be a simple question, but I don’t know the name of what I’m trying to do, so I don’t know how to search for it.

Basically when I am in terminal (linux command line) and I type

$ python do_something.py stuff

      

I want to stuff

mean something to my script. So two questions:

  • How it's called?
  • How can i do this?
+3


source to share


2 answers


The easiest way is to do_something.py

script to import sys

and access the "stuff" command line argument as sys.argv(1)

. There are, of course, many pleasant ways.



+3


source


What you are asking for is called argument parsing.

To do this correctly, you must finally use argparse .

It is a neat but very powerful library to help you parse arguments more efficiently. Also, by default, your scripts handle the arguments appropriately on Linux.

Basic example:

import argparse

parser = argparse.ArgumentParser(description='My argparse program')

parser.add_argument('--verbose',
    action='store_true',
    help='sets output to verbose' )

args = parser.parse_args()

if args.verbose:
    print("~ Verbose!")
else:
    print("~ Not so verbose")

      

Then you can do cool things like:



$ python3 myscript.py --verbose
~ Verbose!

      

And even colder, it provides an automatic argument --help

(or -h

):

$ python3 myscript.py --help
usage: myscript.py [-h] [--verbose]

My argparse program

optional arguments:
  -h, --help  show this help message and exit
  --verbose   sets output to verbose

      

It is a library that allows you to easily do complex things like:

./myscript.py --password=no -c -o --keep_moving --name="Robert"

      

Here is a link to a good tutorial from which the above example was loosely adapted.

+2


source







All Articles