Example #1
0
    def __readIniFile(self, configPath, useEnv=False, **kwargs):
        """Internal method to read INI-style configuration file using standard ConfigParser/configparser library.

        Args:
            configPath (str): Configuration file path
            **kwargs: (dict) passed to ConfigParser/configparser

        Returns:
            object: On success a ConfigParser dictionary-like object

        """
        _ = kwargs
        if useEnv:
            # Note that environmetal variables are still lowercased.
            logger.debug("Using enviroment length %d", len(os.environ))
            configP = cp(os.environ, default_section=self.__defaultSectionName)
        else:
            configP = cp(default_section=self.__defaultSectionName)
        try:
            # This is to avoid case conversion of option names
            # configP.optionxform = str
            configP.optionxform = lambda option: option
            configP.sections()
            configP.read(configPath)
            return configP
        except Exception as e:
            logger.error("Failed reading INI configuration file %s with %s",
                         configPath, str(e))
        return configP
Example #2
0
    def __createConfigParseObj(self, dObj, delimiter=","):
        """Internal method to create a configparser object from a dictionary representation
        of configuration sections and objects.

        The dictionary object must conform to the simple configparser data model. For instance:

            d{'sectionName1': {'option1': value2, 'option2': value2, ... }, ... }

        """
        cpObj = cp()
        try:
            for sK, sV in dObj.items():
                if sK != self.__defaultSectionName:
                    cpObj.add_section(sK)
                for oK, oV in sV.items():
                    if isinstance(oV, (list, tuple, set)):
                        cpObj.set(sK, oK, delimiter.join(oV))
                    elif isinstance(oV, (dict)):
                        continue
                    else:
                        cpObj.set(sK, oK, oV)
        except Exception as e:
            logger.exception("Failing with %s", str(e))

        return cpObj
def fetch_creds():
    script_dir = os.path.dirname(__file__)
    conf_file_path = os.path.join(script_dir, "conf.ini")
    conf = cp()
    conf.read(conf_file_path)
    uname = conf.get('email', 'uname')
    pwd = conf.get('email', 'pwd')
    pwd = bd(pwd).decode("utf-8")
    return uname, pwd
def ConfigParser(*args, **kwargs):
    # Wonky lazy loader workaround (since this library is not required for splunk-embeded (TA)
    # version), but this class is used by multiple methods (so we can't simply inline the import)

    try:
        # New name under Python 3
        from configparser import ConfigParser as cp
    except ImportError:
        # Use backported config parser for Python 2.7 for proper Unicode support
        from backports.configparser import ConfigParser as cp
    # All future accesses of 'ConfigParser' will go directly to this class
    globals()["ConfigParser"] = cp
    return cp(*args, **kwargs)
Example #5
0
	def chkconfig(self):
		home = self.home # XXX
		cname = os.path.join(home, 'config')
		if not os.path.isdir(home):
			os.mkdir(home)
		os.chdir(home)

		config = cp()
		config.read(cname)

		changed = False

		if not config.has_section("user"):
			config.add_section("user")
	
		try:
			username = config.get("user", "username")
		except configparser.NoOptionError:
			username = input("Username: "******"user", "password")
		except configparser.NoOptionError:
			password = gp()
			changed = True
	
		if changed == True:
			config.set("user", "password", password)
			config.set("user", "username", username)
			mask = os.umask(0o077)
			config.write(open(cname, 'w'))
			os.umask(mask) # mask off global read
			print("Wrote configuration ({}).".format(cname))
			print("If you need to change your")
			print("details, please edit this file.")
			print()

		self.username = username
		self.password = password
		self.protocol = 1
		self.clientver = 0.1
		self.client = "pyvndb"
Example #6
0
    def chkconfig(self):
        home = self.home  # XXX
        cname = os.path.join(home, 'config')
        if not os.path.isdir(home):
            os.mkdir(home)
        os.chdir(home)

        config = cp()
        config.read(cname)

        changed = False

        if not config.has_section("user"):
            config.add_section("user")

        try:
            username = config.get("user", "username")
        except configparser.NoOptionError:
            username = input("Username: "******"user", "password")
        except configparser.NoOptionError:
            password = gp()
            changed = True

        if changed == True:
            config.set("user", "password", password)
            config.set("user", "username", username)
            mask = os.umask(0o077)
            config.write(open(cname, 'w'))
            os.umask(mask)  # mask off global read
            print("Wrote configuration ({}).".format(cname))
            print("If you need to change your")
            print("details, please edit this file.")
            print()

        self.username = username
        self.password = password
        self.protocol = 1
        self.clientver = 0.1
        self.client = "pyvndb"
Example #7
0
 def __init__(self,cfgName,environment):
     
     super(MOT,self).__init__(environment)
     
     cfg = cp()
     cfg.read(cfgName)
     
     self.notifier = CMD(environment)
     self.notifier.command = 'NTF'
     
     self.controller = AGUC8(cfg.get('PORT','com'),[cfg.get('CONTROLLER','channel')],
                             cfg.get('CONTROLLER','x'),cfg.get('CONTROLLER','y'),cfg.get('CONTROLLER','ampx'),cfg.get('CONTROLLER','ampy'))
     
     self.respDict = {'M':self.controller.move,
                      'S':self.controller.stop,
                      'SZ':self.controller.setZero,
                      'GZ':self.controller.goToZero,
                      'UU':self.controller.moveUpUp,
                      'UD':self.controller.moveUpDown,
                      'DU':self.controller.moveDownUp,
                      'DD':self.controller.moveDownDown,}
Example #8
0
# 控制节点

#控制节点发送任务程序和切片后的数据给各自处理的节点
#节点0返回规约后的结果
from multiprocessing.connection import Listener

from multiprocessing import Pool
import time,os,sys
from configparser import ConfigParser as cp



#读取配置文件
conf = cp()
conf.read('conf_controller.ini')
conf.sections()



#获取配置文件
port = conf.getint('server', 'port')
host = conf.get('server', 'host')



def control(i,n):
    addr = (host, port+i)
    # 开启监听器
    ctler = Listener(addr)
    print("-----等待一个新客户端到来-----:",addr)
    ctl = ctler.accept()
Example #9
0
 def __init__(self, path):
     self.d = cp()
     self.d.read(path)
     if not self.d.sections():
         raise Exception('path is not cfg file')
Example #10
0
import threading
from configparser import ConfigParser as cp
import sys
import os
from picamera import PiCamera
import board
import I2C_LCD_driver


GPIO.setmode(GPIO.BCM)

armed = False
tripped = False
running = True
pressed = False
config_file = cp()
config_file.read('./config.ini')
images_path = "/home/pi/CIS251/CIS251_GP/images"
#Variable for current number pressed on keypad
curr_num = 15
code = ''
camera = PiCamera()
mylcd = I2C_LCD_driver.lcd()


#2d array for matrix keypad
matrix = [  [1,2,3],
            [4,5,6],
            [7,8,9],
            [0]     ]
Example #11
0
from requests import get, post
from bs4 import BeautifulSoup as bs
from configparser import ConfigParser as cp
import os

#read the config file
config = cp()
config.read("local.conf")
config = config["DEFAULT"]

WEBHD = "http://webhd1.ttu.edu.tw/"
SHARE_KEY = config["SHARE_KEY"]
SHARE_PWD = config["SHARE_PWD"]

LOGIN_DATA = {'sharekey': SHARE_KEY, 'Locale': 'zh-TW', 'Submit': '進入社群'}
INPUTPWD = {'inputpwd': SHARE_PWD, 'Sent': '送出'}

res = post(WEBHD + "share/sharehd.php", data=LOGIN_DATA)
res = post(WEBHD + "share/sharehd.php", data=INPUTPWD, cookies=res.cookies)
soup = bs(res.text, 'html5lib')
sel = soup.select('.cistab a')
os.mkdir(SHARE_KEY)
for link in sel:
    res = get(WEBHD + link['href'], cookies=res.cookies, stream=True)
    filename = res.headers['Content-Disposition'].encode(
        'latin1', 'ignore').decode('big5')[9:]
    print("Saving " + filename)
    with open(SHARE_KEY + "/" + filename, 'wb') as file:
        for chunk in res:
            file.write(chunk)
        file.close()
Example #12
0
# 计算节点
from multiprocessing.connection import Client,Listener
from configparser import ConfigParser as cp
import sys,os


#读取序列号
node = sys.argv[1]
node = int(node)

#读取配置文件,用于建立第一个socket
conf = cp()
conf.read('conf_computer.ini')
# print(conf.sections())
port = conf.getint('server','port')
host = conf.get('server','host')
addr = (host,port+node)


# 读取配置文件,用于开启第二个socket,用于等待其他节点的结果,并规约
conf2 = cp()
conf2.read('conf_computer.ini')
# print(conf2.sections())
port2 = conf2.getint('compute', 'port')
host2 = conf2.get('compute', 'host')
addr2 = (host2, port2)

#建立与控制节点的连接
cpter = Client(addr)
total_node = cpter.recv()
role = cpter.recv()
Example #13
0
import datetime
import pymysql
import cx_Oracle
from configparser import RawConfigParser as cp
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

sys.argv.extend([
    'temp1', 'temp2'
])  # 'temp' is a place holder item in sys.argv to bypass list index exception

# Initializing db constants
db_env = None

# Reading environment variables from config.ini
env = cp()
env.read('config.ini')
if not (all(x in env.sections() for x in ['dev', 'test', 'impl'])):
    raise Exception('Please set environment variables in config.ini')

# Validation of CLI arguments
if sys.argv[1] not in env.sections():
    raise Exception('Invalid env or env not listed in config.ini')
else:
    db_env = sys.argv[1]

in_data_path = os.path.join(os.getcwd(), 'data_in')
out_data_path = os.path.join(os.getcwd(), 'data_out')

msql_cred = {
    'user': env.get('DEFAULT', 'msql_user'),
Example #14
0
def read_ini(src):
    conf = cp()
    conf.read(src, encoding='utf8')
    for i in conf['county']:
        print(i)
from requests import get, post
from bs4 import BeautifulSoup as bs
from configparser import ConfigParser as cp
import os

#read the config file
config = cp()
config.read("local.conf")
config = config["DEFAULT"]

WEBHD = "http://webhd1.ttu.edu.tw/"
SHARE_KEY = config["SHARE_KEY"]
SHARE_PWD = config["SHARE_PWD"]

LOGIN_DATA = {'sharekey': SHARE_KEY, 'Locale': 'zh-TW', 'Submit':'進入社群'}
INPUTPWD = {'inputpwd': SHARE_PWD, 'Sent':'送出'}

res = post(WEBHD + "share/sharehd.php", data=LOGIN_DATA)
res = post(WEBHD + "share/sharehd.php", data=INPUTPWD, cookies=res.cookies)
soup = bs(res.text, 'html5lib')
sel = soup.select('.cistab a')
os.mkdir(SHARE_KEY)
for link in sel:
	res = get(WEBHD + link['href'], cookies=res.cookies, stream=True)
	filename = res.headers['Content-Disposition'].encode('latin1', 'ignore').decode('big5')[9:]
	print("Saving " + filename)
	with open(SHARE_KEY + "/" + filename, 'wb') as file:
		for chunk in res:
			file.write(chunk)
		file.close()
	print("Done!")
Example #16
0
        '-c',
        required=False,
        help="arquivo de configuracao",
        dest='configfile',
    )

    ap.add_argument(
        "message",
        help="mensagen que sera enviada ao destinatario ou um arquivo de texto",
        metavar='MESSAGE',
    )

    args = vars(ap.parse_args())

    configfile = args['configfile'] if args['configfile'] else ''

    if os.path.exists(configfile):
        config = cp(interpolation=ei())
        config.read(configfile)
        sender = config.get('global', 'sender')
        label = config.get('global', 'label')
        footer = config.get('global', 'footer')

    rctp = args['rctp']
    subject = args['subject'] if args['subject'] else 'Sem assunto'
    message = args['message']
    if os.path.exists(message):
        with open(message, 'r') as fp:
            message = fp.readlines()
    sendmail(rctp, subject, message)
Example #17
0
import openpyxl as xl
import xlwings as xw
from Workcell import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from configparser import ConfigParser as cp
try:
    cfg = cp()
    cfg.read('setup.ini')
    MAX_ROW = cfg.getint('setup', 'MAX_ROW')
except:
    MAX_ROW = 1000


##################################################
#       Abstract class to handle worksheet
##################################################
class Worksheet(object):

    ##################################################
    #       Initial method
    ##################################################
    def __init__(self, sheet=None, sheet_wr=None):
        self._worksheet = sheet
        self._worksheet_wr = sheet_wr
        self._rows = []
        self._min_row = 0
        self._max_row = None
        self._cols = []
        self._min_col = 0
        self._max_col = None
Example #18
0
threadsRunning = {
    'relay': False,
    'polling': False,
    'waterOn': False,
    'waterOff': False,
    'foodOn': False,
    'foodOff': False
}

#Relay pin setup
#Must be set up as inputs, so relays stay off
GPIO.setup(pins[0], GPIO.IN)
GPIO.setup(pins[1], GPIO.IN)

#create configparser object
config_ini = cp()
config_ini.read('./config.ini')


#function to read config.ini and return variables
#and add them to a list
def configRead(section, setting, list):
    value = config_ini[section][setting]
    if section == 'TIMING' and value != '0':
        list.append(value)
    if section != 'TIMING' and value != '0':
        list.append(int(value))


#fill lists with data from config.ini
configRead('WATERBOWL', 'low_water', waterThresh)