Search code examples
pythoncommand-lineterminalargv

Error using Argv while running python in terminal


I use argv to pass in unique arguments to python scripts while in terminal. Very useful when running same program on multiple unique files (this program parses an xml file for certain things). I have built three different programs that serve unique purposes.

I am aggregating my programs to one .py file so that I can use 'import' within the actual running instance of python and then go one by one through the files:

>>>import xml
>>>xml.a()
>>>xml.b()
>>>xml.c()

How can I pass arguments to these programs on the fly? I'm getting a syntax error when I place the arguments after calling the program in this way.

>>>xml.a() file1.xml file1.csv
           ^
>>>SyntaxError: invalid syntax

Solution

  • You pass arguments to functions in Python by placing them between the parentheses (these are called "parameters," see documentation). So you'll need to modify your functions so that they can take arguments (rather than read from sys.argv), and then run the function like:

    my_library.py

    def function1(filename):
        print filename
    

    Interpreter

    >>> import my_library
    >>> my_library.function1("file1.xml")
    >>> file1.xml
    

    If you want your function be able to process an indefinite number of arguments (as you can with sys.argv), you can use the * syntax at the end of your arguments list to catch the remaining parameters as a list (see documentation). For example:

    my_library.py

    def function1(*filenames):
        for filename in filenames:
            print filename
    

    Interpreter

    >>> import my_library
    >>> my_library.function1("file1.xml", "file2.csv", "file3.xml")
    file1.xml
    file2.csv
    file3.xml