gpt4 book ai didi

python argparse.ArgumentParser 读取配置文件

转载 作者:行者123 更新时间:2023-11-28 22:22:54 25 4
gpt4 key购买 nike

我正在尝试添加开关 -c 并指定配置文件。我现在使用 config.dat 让它工作,但是当我使用 -c 并指定一个新的 .dat 时,它使用默认的 config.dat....

知道我哪里出错了吗?

#!/usr/bin/python3
import argparse
import shutil

parser = argparse.ArgumentParser(description='Copy multiple Files from a specified data file')
parser.add_argument('-c', '--configfile', default="config.dat",help='file to read the config from')


def read_config(data):
try:
dest = '/home/admin/Documents/backup/'
#Read in date from config.dat
data = open('config.dat')
#Interate through list of files '\n'
filelist = data.read().split('\n')
#Copy through interated list and strip white spaces and empty lines
for file in filelist:
if file:
shutil.copy(file.strip(), dest)
except FileNotFoundError:
pass

args =parser.parse_args()
read = read_config(args.configfile)
args =parser.parse_args()

最佳答案

仔细查看您在第 14 行所做的事情。即使您正在检索并将 --configfile 参数分配给 args,您仍在使用字符串文字 data = open('config.dat') 而不是传递 data(这是作为参数传递给函数 的配置文件的参数值读取配置):

def read_config(data):
try:
dest = '/home/admin/Documents/backup/'
#Read in date from config.dat
data = open(data)
...

我还会更改您传递给 read_config 的参数 data 的命名——这有点模棱两可。您知道此函数需要一个文件名作为参数,所以为什么不简单地称它为 filename

def read_config(filename):
import pdb; pdb.set_trace()
try:
dest = '/home/admin/Documents/backup/'
#Read in date from config.dat
data = open(filename)
#Interate through list of files '\n'
filelist = data.read().split('\n')
#Copy through interated list and strip white spaces and empty lines
for file in filelist:
if file:
shutil.copy(file.strip(), dest)
except FileNotFoundError:
pass

关于python argparse.ArgumentParser 读取配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47399875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com