Python,使用选项变量作为文件名
我试图使用Python选项/变量作为脚本中将使用的filename.csv文件的基础 这是我的密码:Python,使用选项变量作为文件名,python,variables,csv,argparse,Python,Variables,Csv,Argparse,我试图使用Python选项/变量作为脚本中将使用的filename.csv文件的基础 这是我的密码: def get_args(): '''This function parses and return arguments passed in''' # Assign description to the help doc global hostname global username global password global file
def get_args():
'''This function parses and return arguments passed in'''
# Assign description to the help doc
global hostname
global username
global password
global file
parser = argparse.ArgumentParser()
parser.add_argument('--hostname', required=True)
parser.add_argument('--username', default='root', type=str)
parser.add_argument('--password', default='(&653hE@lU')
hostname = args.hostname
username = args.username
password = args.password
args = parser.parse_args()
file = hostname.csv
我在运行时遇到以下错误:
./4collect.py --hostname bar
Traceback (most recent call last):
File "./4collect.py", line 82, in <module>
get_args()
File "./4collect.py", line 67, in get_args
parser.add_argument('--file', default=format(args.hostname)).csv
AttributeError: '_StoreAction' object has no attribute 'csv'
/4collect.py--主机名栏
回溯(最近一次呼叫最后一次):
文件“/4collect.py”,第82行,在
获取参数()
文件“/4collect.py”,第67行,在get_参数中
parser.add_参数('--file',default=format(args.hostname)).csv
AttributeError:“\u StoreAction”对象没有属性“csv”
您试图访问名为主机名
的变量的csv
属性,该属性当然不存在,因为主机名
只是一个字符串,而字符串没有.csv
属性
如果您试图通过将.csv
附加到主机名的值来创建文件名,则需要类似以下内容:
file = '%s.csv' % hostname
或:
此外,在访问
args.hostname
之前,您需要调用parser.parse_args()
,代码示例无法生成您显示的错误.csv
位于错误的位置。
file = hostname + '.csv'