Python command line parameters

62,871

Solution 1

This line

res = os.system(sys.argv(1)) sys.argv(2)

Is wrong in a couple of ways.

First, sys.argv is a list, so you use square brackets to access its contents:

sys.argv[1]
sys.argv[2]

Second, you close out your parentheses on os.system too soon, and sys.argv(2) is left hanging off of the end of it. You want to move the closing parenthesis out to the very end of the line, after all of the arguments.

Third, you need to separate the arguments with commas, a simple space won't do.

Your final line should look like this:

res = os.system(sys.argv[1], sys.argv[2])

Solution 2

A far, far better way to do this is with the argparse library. The envoy wrapper library makes subprocess easier to work with as well.

A simple example:

import argparse
import envoy

def main(**kwargs):
    for key, value in kwargs.iteritems():
        print key, value
    cmd = '{0} {1}'.format(kwargs['program'], ' '.join(kwargs['infiles']))
    r = envoy.run(cmd)
    print r.std_out
    print r.std_err

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Get a program and run it with input', version='%(prog)s 1.0')
    parser.add_argument('program', type=str, help='Program name')
    parser.add_argument('infiles', nargs='+', type=str, help='Input text files')
    parser.add_argument('--out', type=str, default='temp.txt', help='name of output file')
    args = parser.parse_args()
    main(**vars(args))

This reads in the arguments, parses them, then sends them to the main method as a dictionary of keywords and values. That lets you test your main method independently from your argument code, by passing in a preconstructed dictionary.

The main method prints out the keywords and values. Then it creates a command string, and passes that to envoy to run. Finally, it prints the output from the command.

If you have pip installed, envoy can be installed with pip install envoy. The easiest way to get pip is with the pip-installer.

Solution 3

sys.argv is a list, and is indexed using square brackets, e.g. sys.argv[1]. You may want to check len(sys.argv) before indexing it as well.

Also, if you wanted to pass parameters to os.system(), you might want something like os.system(' '.join(sys.argv[1:])), but this won't work for arguments with spaces. You're better off using the subprocess module.

Solution 4

sys.argv is a list

import sys, string, os
print sys.argv

res = os.system(sys.argv[1]) sys.argv[2]
print res

Solution 5

If you are running Python 2.7 it is recommended to use the new subprocess module.

In this case you would write

import sys, subprocess
result = subprocess.check_output(sys.argv[1], sys.argv[2])
Share:
62,871

Related videos on Youtube

Patrick
Author by

Patrick

Updated on July 28, 2020

Comments

  • Patrick
    Patrick over 3 years

    I am just starting with python so I am struggling with a quite simple example. Basically I want pass the name of an executable plus its input via the command line arguments, e.g.:

    python myprogram refprogram.exe refinput.txt
    

    That means when executing myprogram, it executes refprogram.exe and passes to it as argument refinput. I tried to do it the following way:

    import sys, string, os
    print sys.argv
    
    res = os.system(sys.argv(1)) sys.argv(2)
    print res
    

    The error message that I get is:

    res = os.system(sys.argv(1)) sys.argv(2)
                               ^
    SyntaxError: invalid syntax
    

    Anyone an idea what I am doing wrong?

    I am running Python 2.7

    • LarsH
      LarsH over 10 years
      I wish my computer would give me an error massage. :-)
  • Admin
    Admin about 12 years
    Agreed in general (argparse is awesome), though for a beginner's utlity script, it may be overkill.
  • Spencer Rathbun
    Spencer Rathbun about 12 years
    @delnan It solves so many problems, that I think it is better just to bite the bullet and learn it. I've also added a bit on using envoy instead of os.command since I missed that in the original question.
  • user1066101
    user1066101 about 12 years
    It's never overkill. Utility scripts have a way of becoming permanent production features.
  • El Yobo
    El Yobo almost 12 years
    docs.python.org/dev/howto/argparse.html is a "more gentle" introduction to argparse for those unfamiliar with it
  • LarsH
    LarsH over 10 years
    It's never overkill? Good grief ... Sometimes, YAGNI.