45

I'm testing some python code that parses command line input. Is there a way to pass this input in through IDLE? Currently I'm saving in the IDLE editor and running from a command prompt.

I'm running Windows.

2
  • 1
    What's wrong with testing on the command line?
    – S.Lott
    Jan 27, 2010 at 20:23
  • 1
    As of 3.7.4 and 3.8.0b2, use Run ... Customized on the Run menu. Jul 21, 2019 at 20:45

12 Answers 12

36

It doesn't seem like IDLE provides a way to do this through the GUI, but you could do something like:

idle.py -r scriptname.py arg1 arg2 arg3

You can also set sys.argv manually, like:

try:
    __file__
except:
    sys.argv = [sys.argv[0], 'argument1', 'argument2', 'argument2']

(Credit http://wayneandlayne.com/2009/04/14/using-command-line-arguments-in-python-in-idle/)

2
  • ` sys.argv = [sys.argv[0], 'argument1', 'argument2', 'argument2']` works fine, why are you reading file path in try
    – Pyd
    Jan 14, 2018 at 13:45
  • 1
    @pyd: to make that code run only when launched from IDLE.
    – user
    Apr 10, 2019 at 2:43
12

In a pinch, Seth's #2 worked....

2) You can add a test line in front of your main function call which supplies an array of arguments (or create a unit test which does the same thing), or set sys.argv directly.

For example...

sys.argv = ["wordcount.py", "--count", "small.txt"]
1
  • Run the sys.argv command once in the IDLE shell; then use execfile('wordcount.py') to run the script, with those arguments.
    – Erica Kane
    Mar 7, 2015 at 2:56
6

Here are a couple of ways that I can think of:

1) You can call your "main" function directly on the IDLE console with arguments if you want.

2) You can add a test line in front of your main function call which supplies an array of arguments (or create a unit test which does the same thing), or set sys.argv directly.

3) You can run python in interactive mode on the console and pass in arguments:

C:\> python.exe -i some.py arg1 arg2
4

Command-line arguments have been added to IDLE in Python 3.7.4+. To auto-detect (any and older) versions of IDLE, and prompt for command-line argument values, you may paste (something like) this into the beginning of your code:

#! /usr/bin/env python3

import sys

def ok(x=None):
      sys.argv.extend(e.get().split())
      root.destroy()


if 'idlelib.rpc' in sys.modules:

      import tkinter as tk

      root = tk.Tk()
      tk.Label(root, text="Command-line Arguments:").pack()

      e = tk.Entry(root)
      e.pack(padx=5)

      tk.Button(root, text="OK", command=ok,
                default=tk.ACTIVE).pack(pady=5)

      root.bind("<Return>", ok)
      root.bind("<Escape>", lambda x: root.destroy())

      e.focus()
      root.wait_window()

You would follow that with your regular code. ie. print(sys.argv)

Note that with IDLE in Python 3.7.4+, when using the Run... Customized command, it is NOT necessary to import sys to access argv.

If used in python 2.6/2.7 then be sure to capitalize: import Tkinter as tk

For this example I've tried to strike a happy balance between features & brevity. Feel free to add or take away features, as needed!

enter image description here

5
  • My other answer is much more succinct and would work just as well. This one provides a fancy little dialog box to match up with the IDLE GUI.
    – veganaiZe
    Aug 4, 2017 at 21:43
  • Adding a google calendar reminder to update this every so often. Apr 1, 2018 at 14:08
  • 1
    Hey, it started moving after a friendly reminder! Let's hope this time it won't hang again. Thank you for referencing the issue and the pull request here.
    – user
    Jun 2, 2019 at 19:50
  • 1
    New update ;-). A revised PR for 5680 has been applied. As of 3.7.4 and 3.8.0b2, use Run ... Customized on the Run menu. Jul 21, 2019 at 20:46
  • Thanks TJR! You should be the BDFL. Python is you, you are Python.
    – veganaiZe
    Jul 22, 2019 at 20:26
2

Based on the post by danben, here is my solution that works in IDLE:

try:  
    sys.argv = ['fibo3_5.py', '30']  
    fibonacci(int(sys.argv[1]))  
except:  
    print(str('Then try some other way.'))  
2

Auto-detect IDLE and Prompt for Command-line Arguments

#! /usr/bin/env python3

import sys

# Prompt user for (optional) command line arguments, when run from IDLE:
if 'idlelib' in sys.modules: sys.argv.extend(input("Args: ").split())


Change "input" to "raw_input" for Python2.

3
  • Works great on Windows 10 with Python 3.5.2. Jun 25, 2017 at 19:11
  • I needed to catch a KeyError (for "idlelib") outside idle... so I surrounded this with a "try: ... except: KeyError"... your mileage may vary
    – roetzi
    Dec 17, 2018 at 10:58
  • @roetzi I changed it to an if/in to prevent the error without additional cruft.
    – veganaiZe
    Mar 19, 2020 at 6:30
1

This code works great for me, I can use "F5" in IDLE and then call again from the interactive prompt:

def mainf(*m_args):
    # Overrides argv when testing (interactive or below)
    if m_args:
        sys.argv = ["testing mainf"] + list(m_args)

...

if __name__ == "__main__":
    if False: # not testing?
        sys.exit(mainf())
    else:
        # Test/sample invocations (can test multiple in one run)
        mainf("--foo=bar1", "--option2=val2")
        mainf("--foo=bar2")
1

Visual Studio 2015 has an addon for Python. You can supply arguments with that. VS 2015 is now free.

1

import sys

sys.argv = [sys.argv[0], '-arg1', 'val1', '-arg2', 'val2']

//If you're passing command line for 'help' or 'verbose' you can say as:

sys.argv = [sys.argv[0], '-h']

1

IDLE now has a GUI way to add arguments to sys.argv! Under the 'Run' menu header select 'Run... Customized' or just Shift+F5...A dialog will appear and that's it!

1
  • 1
    Sorry, I pressed Shift+F5 and no window asking for parameters appeared. Please specify your IDLE version.
    – Paul
    May 15, 2021 at 12:20
0

Answer from veganaiZe produces a KeyError outside IDLE with python 3.6.3. This can be solved by replacing if sys.modules['idlelib']: by if 'idlelib' in sys.modules: as below.

import argparse
# Check if we are using IDLE
if 'idlelib' in sys.modules:
    # IDLE is present ==> we are in test mode
    print("""====== TEST MODE =======""")
    args = parser.parse_args([list of args])
else:
    # It's command line, this is production mode.
    args = parser.parse_args()
0

There seems like as many ways to do this as users. Me being a noob, I just tested for arguments (how many). When the idle starts from windows explorer, it has just one argument (... that is len(sys.argv) returns 1) unless you started the IDLE with parameters. IDLE is just a bat file on Windows ... that points to idle.py; on linux, I don't use idle.

What I tend to do is on the startup ...

if len(sys.argv) == 1
    sys.argv = [sys.argv[0], arg1, arg2, arg3....] <---- default arguments here

I realize that is using a sledge hammer but if you are just bringing up the IDLE by clicking it in the default install, it will work. Most of what I do is call the python from another language, so the only time it makes any difference is when I'm testing.

It is easy for a noob like me to understand.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.