3

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?
Jivan
  • 21,522
  • 15
  • 80
  • 131
Grant Brown
  • 613
  • 1
  • 8
  • 11
  • 1
    `stuff` is called an argument, and python has a module called argparse to deal with various ways of accepting command line arguments. The documentation and examples are here. https://docs.python.org/3/library/argparse.html – Haleemur Ali Dec 29 '14 at 00:23

2 Answers2

3

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.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • and the fancier ways make use of `sys.argv[1:]` behind the scenes (e.g. `optparse`, `argparse`) – hpaulj Dec 29 '14 at 05:38
  • @hpaulj, sure, and they may well be worth the extra fancy when needed, but perhaps not in the OP's case (hard to say as the Q is very concise about that). – Alex Martelli Dec 29 '14 at 14:59
3

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.

Jivan
  • 21,522
  • 15
  • 80
  • 131