python argparse.ArgumentParser 读取配置文件

标签 python python-3.x copy argparse shutil

我正在尝试添加开关 -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/

相关文章:

macos - 如果 CMake 中的目录内容已更改,如何复制目录?

c# - 覆盖文件最快的方法是什么?

reactjs - 使用 ReactJS 复制到剪贴板

Python 日志记录未使用指定的处理程序

python - Jython subprocess.call() 到 Python

python - 名称 'STDOUT' 未定义,但已导入子流程

python - 2D 游戏中的运动(blitting 时的圆形位置?)

python - Django:获取 TabularInline 模型对象

python - 有没有办法直接在Jupyter cell中调用await?

python-3.x - 我的 Selenium Webdriver 脚本返回一个我不明白的错误