使用 IDLE 将命令行参数传递给 Python 程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4869490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:55:08  来源:igfitidea点击:

Passing Command line argument to Python program using IDLE?

pythoncommand-linecommand-line-argumentspython-idle

提问by Saher Ahwal

I have downloaded a python file xxxxxx.py that is supposed to run on the command line by typing: python xxxxxx.py filename1 filename2and that should take these two files as arguments.

我已经下载了一个 python 文件 xxxxxx.py,它应该通过键入在命令行上运行:python xxxxxx.py filename1 filename2并且应该将这两个文件作为参数。

I was wondering if there is a way I can use IDLE to pass in these arguments. Is there a way other than setting sys.argv?

我想知道是否有一种方法可以使用 IDLE 来传递这些参数。除了设置还有别的方法sys.argv吗?

Thanks

谢谢

采纳答案by slashp

You can do this from the command line with:

您可以从命令行执行此操作:

idle.py -r scriptname.py put arguments here

idle.py -r scriptname.py 把参数放在这里

You can try a different IDE like ActivePython

您可以尝试不同的 IDE,例如 ActivePython

Or you can patch IDLE:

或者您可以修补 IDLE:

http://bugs.python.org/issue5680

http://bugs.python.org/issue5680

回答by Michael Aaron Safyan

It depends on the content of your Python file. If it is well-written, like:

这取决于您的 Python 文件的内容。如果写得很好,比如:

#! /usr/bin/env python

def process(files):
   for file in files:
       # ...

if __name__ == '__main__'
    # some error checking on sys.argv
    process(sys.argv[1:])
    sys.exit(0)

Then you could simply import the python file and run it like:

然后你可以简单地导入 python 文件并像这样运行它:

 import name_of_file

 # ...
       name_of_file.process([file1, file2, file3])
 # ...

So, it really depends on how it is written. If it isn't written well but you can edit it, I would refactor it so that it can be used as a library; otherwise, I would use the subprocess module to invoke the program.

所以,这真的取决于它是如何写的。如果写得不好但可以编辑,我会重构它,以便它可以用作库;否则,我将使用 subprocess 模块来调用该程序。