user3486694
user3486694

Reputation: 85

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

I have created a Python executable using Py2exe. My python script pick values from a config file,but when i compile the script as an executable the values are hardcoded. Is there a way where i can still use my config file to feed values to my executable.

MyPythonScript

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)

Myconfigfile

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

Upvotes: 0

Views: 3159

Answers (1)

boaz_shuster
boaz_shuster

Reputation: 2925

Unfortunately, it's not obvious how you read the username and password from the config file.

In addition to that, may I suggest you to use any third-party to parse your configuration file, for example, configobj and configparser modules.

How to do that?

Assuming that you specify the path to the configuration file, when you run the execution file in the following way:

my_script.exe c:\Myconfigfile.txt

and assuming the configuration file looks like this:

[login]
username = user01
password = 123456

These are two examples of how to do that:

The ConfigParser way

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')

The not so recommended way

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']

Upvotes: 1

Related Questions