When running a python script in IDLE, is there a way to pass in command line arguments (args)?

故事扮演 提交于 2019-11-27 11:26:58

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/)

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"]

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
veganaiZe

A recent patch, for Issue 5680, should finally begin to allow this functionality in future releases of IDLE. In the meantime, if you would like your script to auto-detect 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)

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!

Update: 2018-03-31:

The pull request is still open :(

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 sys.modules['idlelib']: sys.argv.extend(input("Args: ").split())


Change "input" to "raw_input" for Python2.

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")

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

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.'))  

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()

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']

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!