Emile
Emile

Reputation: 2981

How to cleanly pass command-line parameters when test-running my Python script?

So I'm writing Python with IDLE and my usual workflow is to have two windows (an editor and a console), and run my script with F5 to quickly test it.

My script has some non-optional command line parameters, and I have two conflicting desires:

So far my solution has been that if I get no parameters, I look for a params.debug file (that's not under source control), and if so, take that as default params, but it's a bit ugly... so would there be a cleaner, more "standard" solution to this? Do other IDEs offer easier ways of doing this?

Other solutions I can think of: environment variables, having a separate "launcher" script that's the one taking the "official" parameters.

(I'm likely to try out another IDE anyway)

Upvotes: 0

Views: 1409

Answers (3)

Jay Christnach
Jay Christnach

Reputation: 85

Thanks for your question. I also searched for a way to do this. I found that Spyder which is the IDE I use has an option under Run/Configure to enter the command line parameters for running the program. You can even configure different ones for the different editors you have open.

Upvotes: 1

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19184

Python tracker issue 5680 is a proposal to add to Idle a way to set command lines args for F5 Run module. You are free to test any of the proposed patches if you are able to apply them.

In the meanwhile conditionally extending sys.argv as done below should fulfill your requirements.

import sys
in __name__ == '__main__':
    if 'idlelib.PyShell' in sys.modules:
        sys.argv.extend(('a', '-2'))  # add your argments here.
    print(sys.argv)  # in use, parse sys.argv after extending it
# ['C:\\Programs\\python34\\tem.py', 'a', '-2']

Upvotes: 0

hpaulj
hpaulj

Reputation: 231615

With some editors you can define the 'execute' command,

For example with Geany, for Python files, F5 is python2.7 %f. That could be modified to something like python2.7 %f dummy parameters. But I use an attached terminal window and its line history more than F5 like commands.

I'm an Ipython user, so don't remember much about the IDLE configuration. In Ipython I usually use the %run magic, which is more like invoking the script from a shell than from an IDE. Ipython also has a better previous line history than the shell.

For larger scripts I like to put the guts of the code (classes, functions) in one file, and test code in the if __name__ block. The user interface is in another file that imports this core module.

Upvotes: 1

Related Questions