0

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
2
  • you cannot have a function called 1... and sys.argv is for programs run outside the python interpreter. In the interpreter, there are only parameters. Commented Feb 1, 2017 at 19:52
  • Thanks. Changed function names. Only used 1,2,3 for brevity. Commented Feb 1, 2017 at 20:11

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.