[英]How to extend this python script to take in user input by command line instead of prompting?
Currently, I have a python script which takes in a text file, checks for passages enclosed by a tag ##Somethinghere## and asks the user how many times does he/she want to copy it. 目前,我有一个python脚本,该脚本会接收一个文本文件,检查标记## Somethinghere ##所包含的段落,并询问用户他/她要复制多少次。 So for instance if I have the text file: 因此,例如,如果我有文本文件:
Random Text File
##RandomLine1##
Random Line 1
##RandomLine1##
Random Line 2
##RandomLine3##
Random Line 2
##RandomLine3##
End of file
The user is prompted: 提示用户:
Loop "RandomLine1" how many times?
Loop "RandomLine3" how many times?
Once the user enters the numbers, the specific enclosed lines are copied the indicated number of times, and the tags are removed. 用户输入数字后,会将特定的封闭行复制指定的次数,并删除标签。 The text after being copied however many times is output to a designated output file. 但是,多次复制后的文本将输出到指定的输出文件。
To start the script, the command looks like this: 要启动脚本,命令如下所示:
python script.py inputfile outputfile
What I want to do is instead of prompting the user for input, the user can optionally input the number of loops as optional command line parameters. 我想做的是代替提示用户输入,用户可以选择输入循环数作为可选的命令行参数。 Something like: 就像是:
python script.py inputfile outputfile --RandomLine1 2 --RandomLine3 2
Is this possible for a python script? python脚本可能吗? I am attaching the current version of the script below: 我将在下面附加脚本的当前版本:
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()
Yes you can do this by adding default values to your arguments: 是的,您可以通过向参数添加默认值来做到这一点:
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
#...
How about using sys.argv
? 使用sys.argv
怎么样?
sys.argv
returns a list of the arguments your script is passed separated by space, with sys.argv[0]
being the name of the script. sys.argv
返回以空格分隔的脚本传递参数列表,其中sys.argv[0]
为脚本名称。
So for the following program: 因此对于以下程序:
import sys
print sys.argv
when run in the following way: 以以下方式运行时:
python script.py inputfile outputfile --RandomLine1 2 --RandomLine3 2
will produce the following output: 将产生以下输出:
['script.py', 'inputfile', 'outputfile', '--RandomLine1', '2', '--Randomline3', '2']
If you would like to create a dictionary of the lines and the corresponding arguments try something along the lines of the following: 如果您想创建各行的字典以及相应的参数,请尝试以下方法:
# 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
For your input example we would get args_dict == {'RandomLine1': 2, 'RandomLine3': 2}
. 对于您的输入示例,我们将获得args_dict == {'RandomLine1': 2, 'RandomLine3': 2}
。 I think it's pretty easy to see how to use the dictionary for whatever purpose you wish from there. 我认为很容易看到如何从那里将字典用于任何目的。
The above code could of course be done more/less thoroughly depending on how reliable you expect the input to be. 当然,取决于您希望输入的可靠性,以上代码可以做得更多/更少。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.