Grant Brown
Grant Brown

Reputation: 641

Execute python script with a variable from linux shell

This might be an easy 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'm in terminal (linux command line) and I type

$ python do_something.py stuff

I want to get the stuff to mean something for my script. So two questions:

  1. How is this called?
  2. How can I do it?

Upvotes: 3

Views: 2811

Answers (2)

Jivan
Jivan

Reputation: 23068

What you're asking for is called argument parsing.

To do this the proper way, you should definitively use argparse.

It's a neat and yet very powerful library to make argument parsing more efficient. Plus, it makes your scripts manage arguments the proper Linux way, by default.

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 stuff like:

$ python3 myscript.py --verbose
~ Verbose!

And what's even cooler, it provides an automatic --help (or -h) argument:

$ 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

This is the kind of library that allows you to quite easily do complicated stuff like:

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

Here is a link to a nice tutorial from which the above example has been freely adapted.

Upvotes: 3

Alex Martelli
Alex Martelli

Reputation: 881705

The simplest way is for the do_something.py script to import sys and access the "stuff" command-line argument as sys.argv(1). There are many fancier ways, of course.

Upvotes: 3

Related Questions