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

前端 未结 11 838
猫巷女王i
猫巷女王i 2020-12-02 13:08

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

11条回答
  •  悲&欢浪女
    2020-12-02 13:49

    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("", ok)
          root.bind("", 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!

提交回复
热议问题