开发者

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

开发者 https://www.devze.com 2022-12-18 10: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 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.开发者_如何学JAVA

I'm running Windows.


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


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!

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


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


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.


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.


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


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!


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消