2

So I have a fully functional py script running on Ubuntu 12.04, everything works great. Except I don't like my input methods, it's getting annoying as you'll see below. Before I type out the code, I should say that the code takes two images in a .img format and then does computations on them. Here's what I have:

import os

first = raw_input("Full path to first .img file: ")
second = raw_input("Full path to second .img file: ")

print " "


if os.path.exists(first) == True:
    if first.endswith('.img') == False:
        print 'You did not give a .img file, try running again'
        os.sys.exit()
elif os.path.exists(second) == True:
    if second.endswith('.img') == False:
        print 'You did not give a .img file, try running again'
        os.sys.exit()
else:
    print "Your path does not exist, probably a typo. Try again"
    os.sys.exit()

Here's what I want; I want to be able to feed python this input straight from the Terminal. In other words, I want to be able to input in the terminal something like

python myscript.py with the two images as input

This way I could make use of the terminal's tab-key shortcut when specifying paths and stuff. Any ideas/suggestions?

EDIT: Ok so I looked into the parsing, and I think I got down how to use it. Here's my code:

import argparse

import nipy

parser = argparse.ArgumentParser()



parser.add_argument("-im", "--image_input", help = "Feed the program an image", type =     nipy.core.image.image.Image, nargs = 2)

however now I want to be able to use these files in the script by saying something like first = parser[0] second = parse[1] and do stuff on first and second. Is this achievable?

faskiat
  • 689
  • 2
  • 6
  • 21
  • Does this answer your question? [How to read/process command line arguments?](/q/1009860/90527) – outis Oct 23 '22 at 10:57

4 Answers4

7

You want to parse the command line arguments instead of reading input after the program starts.

Use the argparse module for that, or parse sys.argv yourself.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 2
    How do you answer it so fast? Jeez. –  Jul 04 '13 at 16:11
  • Haha yeah that was a pretty fast reply I'm impressed! But OK this seems promising, I'll keep reading into the documentation, thanks – faskiat Jul 04 '13 at 16:26
  • @enginefree: I think he made a python module to check for updates, probably made a better templating language using Python to write better answers. Or maybe its two guys sharing one account, the mysteries of Mr. Pieters will forever remain a mystery! :P – Games Brainiac Jul 04 '13 at 16:31
2

Seeing that the parsing code already exists, all you need to do is accept command-line arguments with Python's sys module:

import sys

first  = sys.argv[1]
second = sys.argv[2]

Or, more generally:

import os
import sys

if __name__ == '__main__':

    if len(sys.argv) < 2:
        print('USAGE: python %s [image-paths]' % sys.argv[0])
        sys.exit(1)

    image_paths = sys.argv[1:]

    for image_path in image_paths:
        if not os.path.exists(image_path):
            print('Your path does not exist, probably a typo. Try again.')
            sys.exit(1)
        if image_path.endswith('.img'):
            print('You did not give a .img file, try running again.')
            sys.exit(1)

NOTES

The first part of the answer gives you what you need to accept command-line arguments. The second part introduces a few useful concepts for dealing with them:

  1. When running a python file as a script, the global variable __name__ is set to '__main__'. If you use the if __name__ == '__main__' clause, you can either run the python file as a script (in which case the clause executes) or import it as a module (in which case it does not). You can read more about it here.

  2. It is customary to print a usage message and exit if the script invocation was wrong. The variable sys.argv is set to a list of the command-line arguments, and its first item is always the script path, so len(sys.argv) < 2 means no arguments were passed. If you want exactly two arguments, you can use len(sys.argv) != 3 instead.

  3. sys.argv[1:] contains the actual command-line arguments. If you want exactly two arguments, you can reference them via sys.argv[1] and sys.argv[2] instead.

  4. Please don't use if os.path.exists(...)==True and if string.endswith(...)==True syntax. It is much clearer and much more Pythonic to write if os.path.exists and if string.endswith(...) instead.

  5. Using exit() without an argument defaults to exit(0), which means the program terminated successfully. If you are exiting with an error message, you should use exit(1) (or some other non-zero value...) instead.

Dan Gittik
  • 3,460
  • 3
  • 17
  • 24
  • Oh wow, I'm sorry I completely bypassed your answer, and it actually answers it best. Thanks very much! – faskiat Jul 05 '13 at 16:27
1

What you want to do is take in command line parameters, and the best way to do that is using a nifty module called argparse. I have listed below a good resource on how to install and use it.

Here is a great resource for argparse. It is a module used to take command line arguments.

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
0

You can probably use sys.argv:

import sys

first = sys.argv[1]
second = sys.argv[2]

Don't forget to check len(sys.argv) before.

Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75