如何从用户输入生成Python配置文件,并插入运行?

如何从用户输入生成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

我已经从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 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')标志,并尝试将其作为纯文本写入。但它不会写入您期望的内容