简体   繁体   English

在终端中运行python时使用Argv时出错

[英]Error using Argv while running python in terminal

I use argv to pass in unique arguments to python scripts while in terminal. 我在终端中使用argv将唯一参数传递给python脚本。 Very useful when running same program on multiple unique files (this program parses an xml file for certain things). 在多个唯一文件上运行同一程序时非常有用(此程序解析xml文件以进行某些操作)。 I have built three different programs that serve unique purposes. 我建立了三个服务于独特目的的不同程序。

I am aggregating my programs to one .py file so that I can use 'import' within the actual running instance of python and then go one by one through the files: 我将程序聚合到一个.py文件,以便可以在python的实际运行实例中使用“导入”,然后逐个浏览文件:

>>>import xml
>>>xml.a()
>>>xml.b()
>>>xml.c()

How can I pass arguments to these programs on the fly? 如何将参数即时传递给这些程序? I'm getting a syntax error when I place the arguments after calling the program in this way. 以这种方式调用程序后放置参数时,出现语法错误。

>>>xml.a() file1.xml file1.csv
           ^
>>>SyntaxError: invalid syntax

You pass arguments to functions in Python by placing them between the parentheses (these are called "parameters," see documentation ). 您可以通过将参数放在括号之间来将参数传递给Python中的函数(这些参数称为“参数”, 请参见文档 )。 So you'll need to modify your functions so that they can take arguments (rather than read from sys.argv ), and then run the function like: 因此,您需要修改函数,以便它们可以接受参数(而不是从sys.argv读取),然后像下面那样运行函数:

my_library.py my_library.py

def function1(filename):
    print filename

Interpreter 口译员

>>> import my_library
>>> my_library.function1("file1.xml")
>>> file1.xml

If you want your function be able to process an indefinite number of arguments (as you can with sys.argv ), you can use the * syntax at the end of your arguments list to catch the remaining parameters as a list ( see documentation ). 如果希望函数能够处理无限数量的参数(就像使用sys.argv ),则可以在参数列表的末尾使用*语法来将其余参数作为列表捕获( 请参阅文档 )。 For example: 例如:

my_library.py my_library.py

def function1(*filenames):
    for filename in filenames:
        print filename

Interpreter 口译员

>>> import my_library
>>> my_library.function1("file1.xml", "file2.csv", "file3.xml")
file1.xml
file2.csv
file3.xml

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM