Passing Command line argument to Python program using IDLE?

Saher Ahwal picture Saher Ahwal · Feb 2, 2011 · Viewed 25.5k times · Source

I have downloaded a python file xxxxxx.py that is supposed to run on the command line by typing: python xxxxxx.py filename1 filename2 and that should take these two files as arguments.

I was wondering if there is a way I can use IDLE to pass in these arguments. Is there a way other than setting sys.argv ?

Thanks

Answer

Michael Aaron Safyan picture Michael Aaron Safyan · Feb 2, 2011

It depends on the content of your Python file. If it is well-written, like:

#! /usr/bin/env python

def process(files):
   for file in files:
       # ...

if __name__ == '__main__'
    # some error checking on sys.argv
    process(sys.argv[1:])
    sys.exit(0)

Then you could simply import the python file and run it like:

 import name_of_file

 # ...
       name_of_file.process([file1, file2, file3])
 # ...

So, it really depends on how it is written. If it isn't written well but you can edit it, I would refactor it so that it can be used as a library; otherwise, I would use the subprocess module to invoke the program.