繁体   English   中英

如何扩展此python脚本以通过命令行而不是提示来接受用户输入?

[英]How to extend this python script to take in user input by command line instead of prompting?

目前,我有一个python脚本,该脚本会接收一个文本文件,检查标记## Somethinghere ##所包含的段落,并询问用户他/她要复制多少次。 因此,例如,如果我有文本文件:

Random Text File

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

Random Line 2

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

End of file

提示用户:

Loop "RandomLine1" how many times?
Loop "RandomLine3" how many times?

用户输入数字后,会将特定的封闭行复制指定的次数,并删除标签。 但是,多次复制后的文本将输出到指定的输出文件。

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

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

是的,您可以通过向参数添加默认值来做到这一点:

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返回以空格分隔的脚本传递参数列表,其中sys.argv[0]为脚本名称。

因此对于以下程序:

import sys
print sys.argv

以以下方式运行时:

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

将产生以下输出:

['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} 我认为很容易看到如何从那里将字典用于任何目的。

当然,取决于您希望输入的可靠性,以上代码可以做得更多/更少。

暂无
暂无

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

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