在IDLE中运行python脚本时,有没有办法传入命令行参数(args)?

发布于 2024-08-19 12:53:30 字数 104 浏览 3 评论 0原文

我正在测试一些解析命令行输入的 python 代码。有没有办法通过 IDLE 传递这个输入?目前,我正在 IDLE 编辑器中保存并从命令提示符运行。

我正在运行 Windows。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

够运 2024-08-26 12:53:30

IDLE 似乎没有提供通过 GUI 执行此操作的方法,但您可以执行以下操作:

idle.py -r scriptname.py arg1 arg2 arg3

您还可以手动设置 sys.argv,例如:

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

(Credit http://wayneandlayne.com/2009/04/14/使用命令行参数in-python-in-idle/

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

幸福丶如此 2024-08-26 12:53:30

在紧要关头,赛斯的#2 起作用了……

2) 您可以在主函数调用前面添加一个测试行
提供一个参数数组(或创建一个单元测试来执行
同样的事情),或者直接设置 sys.argv。

例如...

sys.argv = ["wordcount.py", "--count", "small.txt"]

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"]
吹梦到西洲 2024-08-26 12:53:30

我可以想到以下几种方法:

1)如果需要,您可以直接在 IDLE 控制台上使用参数调用“main”函数。

2)您可以在主函数调用前面添加一个测试行,它提供一个参数数组(或创建一个执行相同操作的单元测试),或者直接设置 sys.argv 。

3)您可以在控制台上以交互模式运行python并传入参数:

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

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
离笑几人歌 2024-08-26 12:53:30

命令行参数已添加到 Python 3.7.4+ 中的 IDLE 。要自动检测(任何和更旧的)IDLE 版本,并提示输入命令行参数值,您可以将以下内容粘贴(类似)到代码的开头:

#! /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()

您可以将其与常规代码放在一起。 IE。 print(sys.argv)

请注意,对于 Python 3.7.4+ 中的 IDLE,当使用 Run...Customized 命令时,它是NOT 需要导入sys才能访问argv

如果在 python 2.6/2.7 中使用,请务必大写: import Tkinter as tk

对于这个示例,我试图在功能和功能之间取得良好的平衡。简洁。您可以根据需要随意添加或删除功能!

在此处输入图像描述

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

蓝梦月影 2024-08-26 12:53:30

根据 danben 的帖子,这是我在 IDLE 中工作的解决方案:

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

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.'))  
青衫儰鉨ミ守葔 2024-08-26 12:53:30

自动检测 IDLE 并提示输入命令行参数

#! /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())

将 Python2 的“input”更改为“raw_input”。

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.

魄砕の薆 2024-08-26 12:53:30

这段代码对我来说非常有用,我可以在 IDLE 中使用“F5”,然后从交互式提示中再次调用:

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

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")
夜未央樱花落 2024-08-26 12:53:30

Visual Studio 2015 有一个 Python 插件。你可以用它来提供论据。 VS 2015 现已免费。

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

风为裳 2024-08-26 12:53:30

import sys

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

//如果您传递 'help' 或 'verbose' 命令行可以表示为:

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

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

我的奇迹 2024-08-26 12:53:30

IDLE 现在有一种 GUI 方式可以将参数添加到 sys.argv!在“运行”菜单标题下,选择“运行...自定义”或只是Shift+F5...将出现一个对话框,就是这样!

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!

高冷爸爸 2024-08-26 12:53:30

veganaiZe 的答案在 python 3.6.3 的 IDLE 之外产生 KeyError。这可以通过将 if sys.modules['idlelib']: 替换为 if 'idlelib' in sys.modules: 来解决,如下所示。

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

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()
彡翼 2024-08-26 12:53:30

似乎有多种方法可以做到这一点,就像用户一样。我是一个菜鸟,我只是测试了参数(有多少)。当空闲从 Windows 资源管理器启动时,它只有一个参数(...即 len(sys.argv) 返回 1),除非您使用参数启动 IDLE。 IDLE只是Windows上的一个bat文件...指向idle.py;在linux上,我不使用idle。

我倾向于做的是在启动时......

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

我意识到这是使用大锤,但如果你只是通过在默认安装中单击它来调出 IDLE,它就会起作用。我所做的大部分工作都是从另一种语言调用 python,所以唯一有区别的时候是在我测试的时候。

对于我这样的菜鸟来说很容易理解。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文