Passing Command line argument to Python program using IDLE?

25,824

Solution 1

You can do this from the command line with:

idle.py -r scriptname.py put arguments here

You can try a different IDE like ActivePython

Or you can patch IDLE:

http://bugs.python.org/issue5680

Solution 2

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.

Share:
25,824
Saher Ahwal
Author by

Saher Ahwal

Software Engineer at Microsoft LinkedIn Profile MEng Thesis: Optimizations to a massively parallel database and support of a shared scan architecture

Updated on February 02, 2020

Comments

  • Saher Ahwal
    Saher Ahwal about 4 years

    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

  • Saher Ahwal
    Saher Ahwal about 13 years
    I just want to pass argument on run time when I run the python script. Is there a way to do that?
  • Saher Ahwal
    Saher Ahwal about 13 years
    if I am on windows. my path now is C:\Python26...etc \ idlelib so I can run idle. But the script is somewhere else and so it cannot find it, what should I do?
  • Saher Ahwal
    Saher Ahwal about 13 years
    Never Mind! I just added the C:\Python26\Lib\idlelib to the path in the Advanced System Settings
  • SomeGuyOnAComputer
    SomeGuyOnAComputer almost 9 years
    Just modify sys.argv within your code. For example sys.argv = ['scriptname.py', 'arg1', 'arg2', 'arg3']
  • Terry Jan Reedy
    Terry Jan Reedy almost 5 years
    A revision of the patch for issue 5680 is in 3.7.4 and 3.8.b2 as Run => Run Customized.
  • Terry Jan Reedy
    Terry Jan Reedy almost 5 years
    @SaherAhwal As of 3.7.4 and 3.8.0b2, use Run ... Customized on the Run menu.