如何使python脚本接受多个位置参数?

如何使python脚本接受多个位置参数?,python,Python,假设我希望python程序接受2个位置参数: 1.输入文件的路径 2.单词词典的路径,也是一个txt文件 有人能教我怎么做吗 import sys print('Name of the script: {0}'.format(sys.argv[0])) if len(sys.argv) == 3: inputfile_path = sys.argv[1] dictionary_path = sys.argv[2] print('First parameter: {0}

假设我希望python程序接受2个位置参数: 1.输入文件的路径 2.单词词典的路径,也是一个txt文件

有人能教我怎么做吗

import sys

print('Name of the script: {0}'.format(sys.argv[0]))

if len(sys.argv) == 3:
    inputfile_path = sys.argv[1]
    dictionary_path = sys.argv[2]
    print('First parameter: {0}'.format(inputfile_path))
    print('Second parameter: {0}'.format(dictionary_path))

你的问题有点含糊,所以我只想回答你的意思

我假设你有这样一个函数:

def function(string1, string2):
''' string 1 and string2 are paths to an input file and a dictionary respectively'''
现在,一般来说,要读取您使用的文件:

file1 = open(string1,'r')
# After opening the file you loop over lines to do what you need to. 
for line in file:
    # Do what you need to
我不确定你想对输入文件做什么,所以我就到此为止

要从字符串加载字典,我们使用
eval()
函数。它实际上运行一个字符串。现在,字典中存储为文本文件的每一行都是一个字符串,因此您所要做的就是遍历整个文件(使用以前的
for line in file
方法),然后运行
eval
以取回字典

例如,请尝试以下简单代码:

#assume string2 is what you get back from the looping
string2 = str({'jack': 4098, 'sape': 4139})

dic = eval(string2)

print dic

希望我给你指出了正确的方向。因为我不确定你到底需要做什么,我真的帮不了你更多

一个单词词典的路径,它也是一个txt文件。
你在这里的意思我刚才的意思是第二个参数用于指定另一个txt文件的路径,该文件恰好用作词典。是的,除了
if
条件中多余的括号,我建议删除:-)@AlexMartelli:oops,谢谢-在过去几周内编写了太多Java,准备删除它:)