如何从用户输入生成Python配置文件,并插入运行?
我已经从Selenium IDE转换了一系列Python webdriver运行。这些运行有1或2个设置,我希望能够使用配置文件来更改这些设置,配置文件是通过运行收集用户输入的脚本创建的,该脚本将设置这2个变量 下面是我使用如何从用户输入生成Python配置文件,并插入运行?,python,file,configuration,configuration-files,configparser,Python,File,Configuration,Configuration Files,Configparser,我已经从Selenium IDE转换了一系列Python webdriver运行。这些运行有1或2个设置,我希望能够使用配置文件来更改这些设置,配置文件是通过运行收集用户输入的脚本创建的,该脚本将设置这2个变量 下面是我使用ConfigParser模块的尝试: import ConfigParser file_path_input = raw_input("Enter path to 'webdriver' directory ex: '/home/user/': ") print "you
ConfigParser
模块的尝试:
import ConfigParser
file_path_input = raw_input("Enter path to 'webdriver' directory ex: '/home/user/': ")
print "you entered", file_path_input
url_input = raw_input("Enter url that the application will point to, ex: 172.31.13.56 or vtm55.example.com: ")
print "you entered", url_input
def createConfig(file_path_input):
"""
Create a config file
"""
config = ConfigParser.ConfigParser()
config.add_section("application_settings")
config.set("application_settings", "file_path_to_use", "file_path_input")
config.set("application_settings", "url_to_use", "url_input")
config.set("application_settings", "settings_info",
"Your application directory is in %(file_path_to_use)s and your application url is %(url_to_use)s")
with open(file_path_input, "wb") as config_file:
config.write(config_file)
raw\u input()
和print()
行工作正常,但似乎根本没有生成配置文件。创建文件后,我希望能够在各种Python webdriver运行中插入变量file\u path\u to\u use
和url\u to\u use
。我建议将输出作为文本编写,而不是使用ConfigParser
。过去,我在使用创建配置文件时遇到了一些奇怪的问题(尽管使用它读取配置文件会更幸运)。如果您转换为使用标准file-i/o只编写文本文件,那么在编写方式上会有更多的特殊性,同时仍然以ConfigParser
以后可以读入的格式编写
createConfig
函数中“文件路径输入”
与文件路径输入不同
'w'
(正常写入)代替'wb'
(写入字节)config
和config\u文件
向后-调用config\u文件
上的write
,然后将要写入的内容传递给它。如果您有一个字符串列表,只需在它们之间循环并使用基本文件I/O写入每个字符串:
configs = ['file_path_to_use:' + file_path_input,
'url_to_use:' + url_input]
with open(file_path_input, 'w') as config_file:
for line in configs:
config_file.write(line + '\n')
样本结果:
file_path_to_use:/home/user/
url_input:vtm.example.com
我没有包括“设置信息”
部分,因为它只是一个回顾:'
上拆分
或分区
您可以放弃使用
ConfigParser
,而是创建一个.py
文件,其中的变量以KEY=VALUE
格式保存,与创建config
文件的方式相同
然后,在代码中编写自己的函数,打开.py
文件(使用和语法,这样它会自动关闭文件而不使用.close()
),并读取它,将其保存为字符串
然后,您可以使用字符串操作获取所需字符串并将其分配给新变量(请记住将其转换为要使用的数据类型,即整数的int()
)。如果不确定,请使用type(
)检查变量的类型。它实际上以小写configparser
和configparser.configparser()
开头。
请更新 您能添加几行打印行来显示正在执行的操作吗?尤其是在使用(打开)
打印文件路径输入和配置文件变量之后?可能会显示出一些错误。见鬼,运行时可能会添加的所有输出。或者,从open file语句中删除binary('b')标志,并尝试将其作为纯文本写入。但它不会写入您期望的内容