如何扩展这个python脚本,以接收命令行而不是提示的用户输入?

2024-05-14 17:32:57 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我有一个python脚本,它接收一个文本文件,检查由标记##Somethinghere#括起来的段落,并询问用户他/她要复制多少次。例如,如果我有文本文件:

Random Text File

##RandomLine1##
Random Line 1
##RandomLine1##

Random Line 2

##RandomLine3##
Random Line 2
##RandomLine3##

End of file

系统将提示用户:

^{pr2}$

一旦用户输入数字,特定的封闭线被复制到指定的次数,并且标签被删除。复制多次后的文本将输出到指定的输出文件。在

要启动脚本,命令如下所示:

python script.py inputfile outputfile

我想做的不是提示用户输入,而是用户可以选择输入循环的数量作为可选的命令行参数。比如:

python script.py inputfile outputfile --RandomLine1 2 --RandomLine3 2

对于python脚本,这是可能的吗?我附上以下脚本的当前版本:

import re
import argparse

pattern = '##([^#]*)##'

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('infile', type=argparse.FileType('r'))
    parser.add_argument('outfile', type=argparse.FileType('w'))
    args = parser.parse_args()

    matcher = re.compile(pattern)
    tagChecker = False
    strList = []
    for line in args.infile:
        if tagChecker is True:
            lineTest = matcher.search(line)
            if lineTest:
                tagChecker = False
                for _ in range(int(raw_input('Loop ' + lineTest.string[2:-3] + ' how many times?')) - 1):
                    for copyLine in strList:
                        args.outfile.write(copyLine)
                new_line = matcher.sub("", line)
                args.outfile.write(new_line)
                strList = []
                continue
            else:
                strList.append(line)
                args.outfile.write(line)
        if tagChecker is False:
            lineTest = matcher.search(line)
            if lineTest:
                tagChecker = True
                new_line = matcher.sub("", line)
                args.outfile.write(new_line)
            else:
                args.outfile.write(line)

    args.infile.close()
    args.outfile.close()

if __name__ == '__main__':
    main()

Tags: 用户脚本parsernewiflineargparseargs
2条回答

是的,您可以通过向参数中添加默认值来完成此操作:

parser.add_argument(" RandomLine1", default=None)
# same for RandomLine2

# ...

if args.RandomLine1 is not None:
    # use args.RandomLine1 as a number
    #...
else:
    # RandomNumber1 is not given in the args
    #...

^{}怎么样?在

sys.argv返回脚本传递的参数列表,用空格分隔,sys.argv[0]是脚本的名称。在

对于以下项目:

import sys
print sys.argv

按以下方式运行时:

^{pr2}$

将产生以下输出:

['script.py', 'inputfile', 'outputfile', ' RandomLine1', '2', ' Randomline3', '2']

如果要创建一个包含行和相应参数的字典,请尝试以下行:

# Get portion of list that isn't the script name or input/output file name
args = sys.argv[3:]
args_dict = {}

i = 0
while i < len(args):
    if args[i].startswith(' '):
        line = args[i].replace(' ', '')
        try:
             args_dict[line] = int(arg[i+1])
        except IndexError:
             print "%s has no argument" % line
        i += 1

对于您的输入示例,我们将得到args_dict == {'RandomLine1': 2, 'RandomLine3': 2}。不管你想怎样用这本字典,我都能看出来。在

当然,根据您期望输入的可靠性,上面的代码可以做得更彻底/更不彻底。在

相关问题 更多 >

    热门问题