parse函数python_python的parse_args()函数
⼀旦我们指定了所有参数,就可以从标准命令⾏输⼊流中解析参数了。为此,我们使⽤parse_args()函数。
现在,可以简单地检查输⼊是否已调⽤特定参数。在这⾥,我们检查args.add的长度,以检查是否有任何从输⼊收到的数据。请注意,参数的值是作为列表获得的。
有两种类型的参数:Positional和Optional。
定位的那些是不需要调⽤任何规范的那些。然⽽,⾸先需要通过名称指定可选参数(以“ - ”符号开头,“ - ”也是速记。)
可以始终使⽤-help或-h可选参数来查看帮助消息。
这是⼀个例⼦(python脚本已保存为add.py):
# importing the required modules
import os
import argparse
# error messages
INVALID_FILETYPE_MSG = "Error: Invalid file format. %s must be a .txt file."
INVALID_PATH_MSG = "Error: Invalid file path/name. Path %s does not exist."
def validate_file(file_name):
'''
validate file name and path.
'''
if not valid_path(file_name):
print(INVALID_PATH_MSG%(file_name))
quit()
elif not valid_filetype(file_name):
print(INVALID_FILETYPE_MSG%(file_name))
quit()
return
def valid_filetype(file_name):
# validate file type
return dswith('.txt')
def valid_path(path):
# validate file path
return ists(path)
def read(args):
# get the file name/path
file_name = ad[0]
# validate the file name/path
validate_file(file_name)
# read and print the file content
with open(file_name, 'r') as f:
ad())
def show(args):
# get path to directory
dir_path = args.show[0]
# validate path
if not valid_path(dir_path):
print("Error: No such directory found.")
exit()
# get text files in directory
files = [f for f in os.listdir(dir_path) if valid_filetype(f)] print("{} text files found.".format(len(files)))
print('\n'.join(f for f in files))
def delete(args):
# get the file name/path
file_name = args.delete[0]
# validate the file name/path
validate_file(file_name)
# delete the file
print("Successfully deleted {}.".format(file_name))
def copy(args):
# file to be copied
file1 = py[0]
# file to copy upon
file2 = py[1]
# validate the file to be copied
validate_file(file1)
# validate the type of file 2
if not valid_filetype(file2):
print(INVALID_FILETYPE_MSG%(file2))
exit()
# copy file1 to file2
with open(file1, 'r') as f1:
with open(file2, 'w') as f2:
f2.ad())
error parse newprint("Successfully copied {} to {}.".format(file1, file2)) def rename(args):
# old file name
old_filename = ame[0]
# new file name
new_filename = ame[1]
# validate the file to be renamed
validate_file(old_filename)
# validate the type of new file name
if not valid_filetype(new_filename):
print(INVALID_FILETYPE_MSG%(new_filename))
exit()

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。