如何将值从配置文件传递给 Python 可执行文件

How to pass values to a Python executable from a config file

我已经使用 Py2exe 创建了一个 Python 可执行文件。我的 python 脚本从配置文件中选取值,但是当我将脚本编译为可执行文件时,这些值是硬编码的。有没有办法让我仍然可以使用我的配置文件为我的可执行文件提供值。

我的Python脚本

driver = webdriver.Firefox()
driver.maximize_window()
driver.get(url)
driver.find_element_by_name("UserName").send_keys(username)
driver.find_element_by_name("Password").send_keys(password)

我的配置文件

url = 'http://testurl'
username = 'testdata'
password = 'testdata'

不幸的是,您如何从配置文件中读取用户名和密码并不明显。

除此之外,我建议您使用任何第三方来解析您的配置文件,例如configobj and configparser 模块。

怎么做?

假设你指定了配置文件的路径,当你运行执行文件的时候是这样的:

my_script.exe c:\Myconfigfile.txt

并假设配置文件如下所示:

[login]
username = user01
password = 123456

这些是如何做到这一点的两个例子:

ConfigParser 方式

import sys, ConfigParser

if len(sys.argv) < 2:
    print "missing configuration file path"

config_path = sys.argv[1]
config = ConfigParser.ConfigParser()
config.readfp(open(config_path))
print config.get('login', 'username'), config.get('login', 'password')

不太推荐的方式

import sys

if len(sys.argv) < 2:
    print "missing configuration file path"

config_path = sys.argv[1]
config_hash = {}
with open(config_path, 'r') as config_stream:
    lines = config_stream.readlines()
for line in lines:
    key_value = line.split('=')
    # skip lines that are not in the "key = value" format
    if len(key_value) != 2:
        continue
    config_hash[key_value[0].strip()] = key_value[1].strip()

print config_hash['username'], config_hash['password']