【问题标题】:How to make Python Configuration File from user input, and insert runs?如何根据用户输入制作 Python 配置文件并插入运行?
【发布时间】:2015-05-21 19:21:43
【问题描述】:

我有一堆从 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_input()print() 行有效,但配置文件似乎根本没有生成。创建文件后,我希望能够在我的各种 Python webdriver 运行中插入变量 file_path_to_useurl_to_use

【问题讨论】:

  • 您能添加几行打印行来显示正在执行的内容吗?特别是在 with(open) 打印 file_path_input 和 config_file 变量之后?可以显示一些错误。哎呀,也许添加运行它时的所有输出。或者,从 open-file 语句中删除二进制 ('b') 标志并尝试将其写为纯文本。
  • 它并没有写出你所期望的内容

标签: python file configuration configuration-files configparser


【解决方案1】:

我建议将您的输出写成文本,而不是使用ConfigParser。过去,我在使用 create 配置文件时遇到过奇怪的问题(尽管使用它来阅读它们会更好)。如果您转换为仅使用标准 file-i/o 写入文本文件,则您可以更具体地编写它,同时仍以 ConfigParser 以后可以读取的格式写入它。

【讨论】:

    【解决方案2】:
    1. 您的缩进有问题,尤其是在 createConfig 函数中。
    2. "file_path_input"file_path_input 不同。
    3. 使用'w'(正常写入)而不是'wb'(写入字节)。
    4. 你有 configconfig_file 向后调用 - 在 config_file 上调用 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
      

      我没有包括 "settings_info" 部分,因为它只是一个回顾。

    5. 然后您可以在重新读入文件时在':'splitpartition

    【讨论】:

      【解决方案3】:

      您可以使用ConfigParser 废弃,而是创建一个.py 文件,其中以KEY=VALUE 格式保存的变量与创建config 文件的方式相同。

      然后在您的代码中,编写您自己的函数来打开.py 文件(使用with 语法,这样它会在没有.close() 的情况下自动关闭文件)并读取它,将其保存为字符串。

      然后您可以使用字符串操作来获取您想要的字符串并将其分配给一个新变量(请记住将其转换为您想要使用的数据类型,即int() 用于整数)。如果不确定,请使用type() 检查变量的类型。

      【讨论】:

        【解决方案4】:

        它实际上以小写的configparserconfigparser.ConfigParser() 开头。 请更新。

        【讨论】:

          猜你喜欢
          • 2020-09-09
          • 1970-01-01
          • 1970-01-01
          • 2016-07-08
          • 1970-01-01
          • 2014-02-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多