def choose(self, index): return Device(self.__platform.get_devices()[index])
sys.path.append(upone_path) from device import Device vec_len = 32 * 320 * 320 streams = 2 # Sample data a = np.arange(0, vec_len, 1).reshape(streams, vec_len // streams).astype('c16') b = np.ones(a.shape, a.dtype) # Pre allocated space for the result nrms = np.empty(streams, a.dtype) # Initialize the Device object on the default device(0) with 2 streams with Device(n_streams=streams) as d: # If using streams, relevant host memory needs to be pinned for async operation d.require_streamable(a, b) # Allocate device memory for each stream to use, and return their references ## Mallocs are always synchronous, and should be done in their own loop to ## avoid synchorizing the otherwise async stream methods for s in d.streams: s.a = s.malloc(a[0].shape, a.dtype) s.b = s.malloc(b[0].shape, b.dtype) # Running the stream async operations for stream_id, s in enumerate(d.streams): s.a.to_device_async(a[stream_id]) s.b.to_device_async(b[stream_id])
import logging from config import CRAWLER_LOG_FILE_PATH from crawler import Crawler from device import Device from path import Path import os package = "com.tencent.mm" root_activity = "com.tencent.mm.ui.LauncherUI" guide_directory = os.path.abspath("./data/wechat_red_packet2") device_serial = "" strings_path = os.path.abspath("./strings/wechat_strings.txt") cluster_dir = os.path.abspath("./data/wechat001") logging.basicConfig(level=logging.DEBUG, filename=CRAWLER_LOG_FILE_PATH, datefmt='%m-%d %H:%M:%S', format='[%(asctime)s] [%(levelname)s] [%(filename)s] [%(funcName)s] - %(message)s') if __name__ == "__main__": logging.info("Program started.") device = Device(device_serial) crawler = Crawler(package, root_activity, device, strings_path, cluster_dir) guide_path = Path() guide_path.load(guide_directory) crawler.follow_guide_path(guide_path)
def createDevice(self, dets): return Device(dets)
def main(): switch = Device(ip='172.31.217.134', username='******', password='******') switch.open() show_boot_config = copy_bootflash(switch)
def __init__(self): self.device = Device("Office computer")
get actual url from the address bar """ url = '' try: element = get_elements(device, 'resource-id', 'org.mozilla.firefox:id/browser_toolbar') url = element.attrib['content-desc'] url = url.split('?')[0] except: pass return url ## directory to top 1m csv files top_1m_path = '/home/h/Desktop/dataCollection/top-1m.csv' device_ids = Device.get_device_identifiers() device = Device(device_ids) top_1m_websites = [] with open(top_1m_path, "rb") as f: reader = csv.reader(f) for row in reader: top_1m_websites.append(row[1]) ### number of websites visiting webnum = 500 urls = top_1m_websites[:webnum] root_path = '/home/h/Desktop/screenshot/' visit_path = '/home/h/Desktop/visit_log/' iteration = 10 bar = progressbar.ProgressBar()
ip_addresses = ip_file_object.readline().strip() ip_address_list = ip_addresses.split(',') for each_ip in ip_address_list: #check to see it the IP address passed is a valid host cmd = shlex.split("ping -n 1 ") cmd.append(each_ip) #print "cmd: ",cmd try: output = subprocess.check_output(cmd) except subprocess.CalledProcessError, e: print each_ip, " is not valid" continue else: switch = Device(ip=each_ip, username='******', password='******') switch.open() shver_command_out = switch.show('show version') result = xmltodict.parse(shver_command_out[1]) #print json.dumps(result, indent=4) sw_version = result['ins_api']['outputs']['output']['body'][ 'kickstart_ver_str'] sw_hostname = result['ins_api']['outputs']['output']['body'][ 'host_name'] sw_chassis = result['ins_api']['outputs']['output']['body'][ 'chassis_id'] sw_chassis_list = sw_chassis.split(' ') sw_model = sw_chassis_list[1]
def __init__(self, devices_serial, pro_click=100, pro_longclick=10, pro_scroll=10, pro_edit=10, pro_naturalscreen=5, pro_leftscreen=10, pro_back=5, pro_home=5, pro_splitscreen=0, app_path=None, is_emulator=True, choice=0, emulator_path=None, android_system=None, root_path=None, resource_path=None, strategy_list=None, testcase_count=None, start_testcase_count=None, event_num=None, timeout=None, policy_name="random", setting_random_denominator=5, serial_or_parallel=None, app_name=None, emulator_name=None, is_login_app=None, rest_interval=None, trace_path=None): logging.basicConfig(level=logging.INFO) self.logger = logging.getLogger('SetDroid') self.enabled = True SetDroid.instance = self self.timer = None self.policy_name = policy_name self.timeout = timeout self.pro_click = pro_click self.pro_longclick = pro_longclick self.pro_scroll = pro_scroll self.pro_home = pro_home self.pro_edit = pro_edit self.pro_naturalscreen = pro_naturalscreen self.pro_leftscreen = pro_leftscreen self.pro_back = pro_back self.pro_splitscreen = pro_splitscreen self.app_path = app_path self.is_emulator = is_emulator self.devices_serial = devices_serial self.devices = [] self.choice = choice self.emulator_path = emulator_path self.android_system = android_system self.resource_path = resource_path self.strategy_list = strategy_list self.testcase_count = testcase_count self.start_testcase_count = start_testcase_count self.event_num = event_num self.app = App(app_path, root_path, app_name) self.setting_random_denominator = setting_random_denominator self.serial_or_parallel = serial_or_parallel self.emulator_name = emulator_name self.is_login_app = is_login_app self.rest_interval = rest_interval self.trace_path = trace_path self.start_time = 0 if root_path is not None: if not os.path.isdir(root_path): os.makedirs(root_path) else: print("None root path") return self.root_path = root_path + self.app.package_name + "/" if not os.path.isdir(self.root_path): os.makedirs(self.root_path) i = 0 for device_serial in devices_serial: device = Device(device_serial=device_serial, is_emulator=is_emulator, device_num=i, rest_interval=rest_interval) self.devices.append(device) i = i + 1 self.executor = Executor( devices=self.devices, app=self.app, strategy_list=self.strategy_list, pro_click=self.pro_click, pro_longclick=self.pro_longclick, pro_scroll=self.pro_scroll, pro_home=self.pro_home, pro_edit=self.pro_edit, pro_naturalscreen=self.pro_naturalscreen, pro_leftscreen=self.pro_leftscreen, pro_back=self.pro_back, pro_splitscreen=self.pro_splitscreen, emulator_path=self.emulator_path, android_system=self.android_system, root_path=self.root_path, resource_path=self.resource_path, testcase_count=self.testcase_count, start_testcase_count=self.start_testcase_count, event_num=self.event_num, timeout=self.timeout, policy_name=self.policy_name, setting_random_denominator=self.setting_random_denominator, serial_or_parallel=self.serial_or_parallel, emulator_name=self.emulator_name, is_login_app=self.is_login_app, rest_interval=self.rest_interval, trace_path=self.trace_path, choice=self.choice)
def __init__(self): self.device = Device("Economic laptop")
load_dotenv() except ImportError: pass parser = argparse.ArgumentParser( description='nRF91 device provisioning example') parser.add_argument('serial', help='nRF91 Serial port') parser.add_argument('-d', help='Enable debug logs', action='store_true') args = parser.parse_args() if args.d: logging.basicConfig(level=logging.DEBUG, format='%(message)s') else: logging.basicConfig(level=logging.INFO, format='%(message)s') dev = Device(args.serial) imei = dev.get_imei() identity = f'urn:imei:{imei}' logging.info('Identity: %s', identity) # Remove previous keys dev.delete_sec_tag(35724861) dev.delete_sec_tag(35724862) # Generate and store Bootstrap keys psk = token_hex(16) dev.store_psk(35724862, identity, psk) coiote = Coiote() coiote.get_device(identity)
if args.logfile: logging.basicConfig(filename=args.logfile, format='%(asctime)s - %(levelname)s: %(message)s', level=logging_level) else: logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', level=logging_level) logging.debug("command line arguments: " + str(vars(args))) hostname = socket.gethostname() collection = DriverCollection(args.xmldir) indi_server = IndiServer(args.fifo, args.conf) indi_device = Device() db_path = os.path.join(args.conf, 'profiles.db') db = Database(db_path) collection.parse_custom_drivers(db.get_custom_drivers()) if args.server == 'standalone': app = Bottle() logging.info('using Bottle as standalone server') else: app = default_app() logging.info('using Apache web server') saved_profile = None active_profile = ""
def __init__(self, app_path=None, device_serial=None, output_dir=None, env_policy=None, event_policy=None, no_shuffle=False, no_textview=False, script_path=None, event_count=None, event_interval=None, event_duration=None, keep_app=None, dont_tear_down=False, quiet=False, with_droidbox=False, use_hierarchy_viewer=False, profiling_method=None, grant_perm=False): """ initiate droidbot with configurations :return: """ logging.basicConfig(level=logging.WARNING if quiet else logging.INFO) self.logger = logging.getLogger('DroidBot') DroidBot.instance = self self.output_dir = output_dir if output_dir is not None: if not os.path.isdir(output_dir): os.mkdir(output_dir) self.dont_tear_down = dont_tear_down self.keep_app = keep_app # if device_serial is None: # # Dirty Workaround: Set device_serial to Default='.*', because com/dtmilano/android/viewclient.py # # set serial to an arbitrary argument. IN connectToDeviceOrExit(..) line 2539f. # # FIXED by requiring device_serial in cmd # device_serial = '.*' self.device = None self.app = None self.droidbox = None self.env_manager = None self.event_manager = None self.enabled = True try: self.device = Device(device_serial=device_serial, output_dir=self.output_dir, use_hierarchy_viewer=use_hierarchy_viewer, grant_perm=grant_perm) self.app = App(app_path, output_dir=self.output_dir) if with_droidbox: self.droidbox = DroidBox(droidbot=self, output_dir=self.output_dir) self.env_manager = AppEnvManager(device=self.device, app=self.app, env_policy=env_policy) self.event_manager = AppEventManager(device=self.device, app=self.app, event_policy=event_policy, no_shuffle=no_shuffle, no_textview=no_textview, event_count=event_count, event_interval=event_interval, event_duration=event_duration, script_path=script_path, profiling_method=profiling_method) except Exception as e: self.logger.warning("Something went wrong: " + e.message) import traceback traceback.print_exc() self.stop() sys.exit(-1)
def __init__(self, song, jack_client): QObject.__init__(self) super(Gui, self).__init__() self._jack_client = jack_client self.setupUi(self) self.clip_volume.knobRadius = 3 self.is_learn_device_mode = False self.queue_out, self.queue_in = Queue(), Queue() self.updateUi.connect(self.update) self.readQueueIn.connect(self.readQueue) self.current_vol_block = 0 self.last_clip = None # Load devices self.deviceGroup = QActionGroup(self.menuDevice) self.devices = [] device_settings = QSettings('superboucle', 'devices') if ((device_settings.contains('devices') and device_settings.value('devices'))): for raw_device in device_settings.value('devices'): self.devices.append(Device(pickle.loads(raw_device))) else: self.devices.append(Device({ 'name': 'No Device', })) self.updateDevices() self.deviceGroup.triggered.connect(self.onDeviceSelect) self.settings = QSettings('superboucle', 'session') # Qsetting appear to serialize empty lists as @QInvalid # which is then read as None :( # Load playlist self.playlist = self.settings.value('playlist', []) or [] # Load paths self.paths_used = self.settings.value('paths_used', {}) self.auto_connect = self.settings.value('auto_connect', 'true') == "true" # Load song self.port_by_name = {} self.initUI(song) self.actionNew.triggered.connect(self.onActionNew) self.actionOpen.triggered.connect(self.onActionOpen) self.actionSave.triggered.connect(self.onActionSave) self.actionSave_As.triggered.connect(self.onActionSaveAs) self.actionAdd_Device.triggered.connect(self.onAddDevice) self.actionManage_Devices.triggered.connect(self.onManageDevice) self.actionPlaylist_Editor.triggered.connect(self.onPlaylistEditor) self.actionScene_Manager.triggered.connect(self.onSceneManager) self.actionPort_Manager.triggered.connect(self.onPortManager) self.actionFullScreen.triggered.connect(self.onActionFullScreen) self.master_volume.valueChanged.connect(self.onMasterVolumeChange) self.bpm.valueChanged.connect(self.onBpmChange) self.beat_per_bar.valueChanged.connect(self.onBeatPerBarChange) self.rewindButton.clicked.connect(self.onRewindClicked) self.playButton.clicked.connect(self._jack_client.transport_start) self.pauseButton.clicked.connect(self._jack_client.transport_stop) self.gotoButton.clicked.connect(self.onGotoClicked) self.recordButton.clicked.connect(self.onRecord) self.clip_name.textChanged.connect(self.onClipNameChange) self.clip_volume.valueChanged.connect(self.onClipVolumeChange) self.beat_diviser.valueChanged.connect(self.onBeatDiviserChange) self.output.activated.connect(self.onOutputChange) self.mute_group.valueChanged.connect(self.onMuteGroupChange) self.frame_offset.valueChanged.connect(self.onFrameOffsetChange) self.beat_offset.valueChanged.connect(self.onBeatOffsetChange) self.revertButton.clicked.connect(self.onRevertClip) self.normalizeButton.clicked.connect(self.onNormalizeClip) self.exportButton.clicked.connect(self.onExportClip) self.deleteButton.clicked.connect(self.onDeleteClipClicked) self.blktimer = QTimer() self.blktimer.state = False self.blktimer.timeout.connect(self.toggleBlinkButton) self.blktimer.start(self.BLINK_DURATION) self.disptimer = QTimer() self.disptimer.start(self.PROGRESS_PERIOD) self.disptimer.timeout.connect(self.updateProgress) self._jack_client.set_timebase_callback(self.timebase_callback) self.show()
from devicemanager import DeviceManager from device import Device device1 = Device("Lamp 1", False) device2 = Device("Lamp 2", False) device3 = Device("Philips hue", True) device4 = Device("Nest", False) manager = DeviceManager() manager.add_device(1, device1) manager.add_device(2, device2) manager.add_device(3, device3) manager.add_device(4, device4) manager.switch_everything_off() for id, device in manager.device_dict.items(): print(id) print(device)
import signal import sys import pingr import os from device import Device import banners devices = [ Device("8.8.8.8", ["*****@*****.**"], interval=5), Device("8.8.8.12", ["*****@*****.**"], interval=5) ] def confirm_loop(message, action): print(message) again = input("Y/n: ") while again.capitalize() == "Y": action() print(f"Continue: {message}?") again = input("Y/n: ") def create_system(): print("ADDING SYSTEM TO MONITOR:") address = input("System Address: ") device = Device(address) devices.append(device) confirm_loop("Do you want to recieve notifications if the system is down?", device.add_monitor)
def main(): credentials: map = getCredentials() token: str = setup(credentials) device = Device(credentials["name"], credentials["password"], token) getStateLoop(device) pass
def testAddDevice1(self, eui64): self.device_dict[eui64] = Device(eui64) device = self.device_dict[eui64] device.deviceState = DeviceState.UNDEFINED
import time from flask import Flask, render_template, jsonify, request, redirect, url_for from device import Device from random import randint from sensor import * # ========= # Default Values # 0 - Temperature # 1 - Moisture # 2 - PH # 3 - Humidity # ========= app = Flask(__name__) device = Device() conn = createConnection() @app.context_processor def inject_user(): return dict(deviceID=device.deviceID) @app.route("/") def renderRoot(): if not device.deviceID: return render_template("device.html") return render_template("index.html") @app.route("/setDevice", methods=["POST"])
def testAddDevice2(self, eui64): self.device_dict[eui64] = Device(eui64) device = self.device_dict[eui64] device.deviceState = DeviceState.ADDED
# except Exception as e: # print(e) import json from device import Device from sys import exit import time # Collect informations about API and client with open('./config.json') as f: config = json.load(f) apiHost = "{ip}:{port}".format(ip=config["api_ip"], port=config["api_port"]) username = config["username"] password = config["password"] nfcPort = config["nfc_port"] displayPort = config["display_port"] displayAddress = config["display_address"] dev = Device(username, password, apiHost, nfcPort, displayPort, displayAddress) # Authentication response = dev.auth() if(response == False): exit() # Wrong credentials print("Authenticated! Room ID associated: {}".format(response["codroom"])) dev.startListen() print("waiting")
def addDevice(self, content): device = Device(content) self.devices[content['device_id']] = device return device.__dict__
from device import Device import sys app = Device(__name__, sys.argv[1]) if __name__ == '__main__': app.run()
show_vpc_command = sw.show('show vpc brief') result_vpc_command = xmltodict.parse(show_vpc_command[1]) peerlink_vlans = result_vpc_command['ins_api']['outputs']['output'][ 'body']['TABLE_peerlink']['ROW_peerlink']['peer-up-vlan-bitset'].split( ",") #for each in peerlink_vlans: # print 'vlan ', each['peer-up-vlan-bitset'] return peerlink_vlans if __name__ == "__main__": # switch = Device(ip='198.18.134.17', username='******',password='******') switch = Device(ip='172.23.193.210', username='******', password='******') switch.open() #vpc_vlans = str(get_vpc_vlans(switch)) vpc_vlans = get_vpc_vlans(switch) print "The following vlan's are being carried over vPC Peer Link." print "Ensure these are not running any routing protos." print vpc_vlans #i = 0 #while i < len(vpc_vlans): # print(vpc_vlans[i]) # i += 1 #for each in vpc_vlans: # print vpc_vlans
def __init__(self, number_of_devices): self.devices = [ Device(self) for x in xrange(number_of_devices) ] #Instantiate device objects, with a default UUID4 id from the Device's constructor. self.device_assignments = OrderedDict( ) #Maintain an ordered dictionary of which patients are assigned which device.
from device import Device sw1 = Device(ip='172.31.217.138', username='******', password='******') sw1.open() command = sw1.show('show int e1/48') print command import xmltodict import json command = sw1.show('sh int e1/48') result = xmltodict.parse(command[1]) print json.dumps(result, indent=4) ip = result['ins_api']['outputs']['output']['body']['TABLE_interface'][ 'ROW_interface']['eth_ip_addr'] print ip mask = result['ins_api']['outputs']['output']['body']['TABLE_interface'][ 'ROW_interface']['eth_ip_mask'] print mask print ip + '/' + mask sh_vlan = sw1.show('sh vl') sh_vlan_dict = xmltodict.parse(sh_vlan[1]) print json.dumps(sh_vlan_dict, indent=4) vlan10_name = sh_vlan_dict['ins_api']['outputs']['output']['body'][ 'TABLE_vlanbrief']['ROW_vlanbrief'][1]['vlanshowbr-vlanname']
def __init__(self, app_path=None, device_serial=None, output_dir=None, env_policy=None, policy_name=None, random_input=False, script_path=None, event_count=None, event_interval=None, timeout=None, keep_app=None, keep_env=False, debug_mode=False, profiling_method=None, grant_perm=False): """ initiate droidbot with configurations :return: """ logging.basicConfig( level=logging.DEBUG if debug_mode else logging.INFO) self.logger = logging.getLogger('DroidBot') DroidBot.instance = self self.output_dir = output_dir if output_dir is not None: if not os.path.isdir(output_dir): os.mkdir(output_dir) html_index_path = pkg_resources.resource_filename( "droidbot", "resources/index.html") stylesheets_path = pkg_resources.resource_filename( "droidbot", "resources/stylesheets") target_stylesheets_dir = os.path.join(output_dir, "stylesheets") if os.path.exists(target_stylesheets_dir): shutil.rmtree(target_stylesheets_dir) shutil.copy(html_index_path, output_dir) shutil.copytree(stylesheets_path, target_stylesheets_dir) self.timeout = timeout self.timer = None self.keep_env = keep_env self.keep_app = keep_app self.device = None self.app = None self.droidbox = None self.env_manager = None self.input_manager = None self.enabled = True try: self.device = Device(device_serial=device_serial, output_dir=self.output_dir, grant_perm=grant_perm) self.app = App(app_path, output_dir=self.output_dir) self.env_manager = AppEnvManager(device=self.device, app=self.app, env_policy=env_policy) self.input_manager = InputManager( device=self.device, app=self.app, policy_name=policy_name, random_input=random_input, event_count=event_count, event_interval=event_interval, script_path=script_path, profiling_method=profiling_method) except Exception as e: self.logger.warning("Something went wrong: " + e.message) import traceback traceback.print_exc() self.stop() sys.exit(-1)
import time import numpy as np import threading from threading import Lock import sys if len(sys.argv) > 1: if sys.argv[1] == '-f': device.debug = False print_lock = Lock() # first set up the IoT system: address = ('localhost', 8881) motion_sensor = Device(address, 'sensor', 'motion') motion_sensor.connect() time.sleep(0.5) door_sensor = Device(address, 'sensor', 'door') door_sensor.connect() time.sleep(0.5) security_system = Device(address, 'device', 'security') security_system.connect() time.sleep(0.5) beacon = Device(address, 'sensor', 'beacon')
def processPushDataMessage(self, request, gateway): """Process a PUSH_DATA message from a LoraWAN gateway Args: request (GatewayMessage): the received gateway message object gateway (Gateway): the gateway that sent the message Returns: True on success, otherwise False """ for rxpk in request.rxpk: # Decode the MAC message message = MACMessage.decode(rxpk.data) # TODO if self._checkDuplicateMessage(message): returnValue(False) # Join Request if message.isJoinRequest(): # Get the application using appeui app = next( (a for a in self.config.apps if a.appeui == message.appeui), None) if app is None: log.info( "Message from {deveui} - AppEUI {appeui} " "does not match any configured applications.", deveui=euiString(message.deveui), appeui=message.appeui) returnValue(False) # Create a new Device, tx parameters and gateway address device = Device(deveui=message.deveui, tx_chan=rxpk.chan, tx_datr=rxpk.datr, gw_addr=request.remote[0]) # If join request is successful, send a join response device = yield self._processJoinRequest(message, app, device) if device: # Save and update the ADR measures yield device.save() if self.config.adrenable: device.updateSNR(rxpk.lsnr) log.info( "Successful Join request from DevEUI {deveui} " "for AppEUI {appeui} | Assigned address {devaddr}", deveui=euiString(device.deveui), appeui=euiString(app.appeui), devaddr=devaddrString(device.devaddr)) self._sendJoinResponse(request, rxpk, gateway, app, device) returnValue(True) else: returnValue(False) # Check this is an active device device = yield self._getActiveDevice(message.payload.fhdr.devaddr) if device is None: log.info("Message from unregistered address {devaddr}", devaddr=devaddrString(message.payload.fhdr.devaddr)) returnValue(False) # Check frame counter if not device.checkFrameCount(message.payload.fhdr.fcnt, self.band.max_fcnt_gap, self.config.fcrelaxed): log.info("Message from {devaddr} failed frame count check.", devaddr=devaddrString(message.payload.fhdr.devaddr)) yield device.save() returnValue(False) # Perform message integrity check. if not message.checkMIC(device.nwkskey): log.info( "Message from {devaddr} failed message " "integrity check.", devaddr=devaddrString(message.payload.fhdr.devaddr)) returnValue(False) # Set the device rx window parameters, remote, gateway and update SNR reading device.tx_datr = rxpk.datr device.rx = self.band.rxparams((device.tx_chan, device.tx_datr), join=False) device.remote = request.remote device.gw_addr = gateway.host device.updateSNR(rxpk.lsnr) yield device.save() # Process MAC Commands commands = [] if message.isMACCommand(): message.decrypt(device.nwkskey) commands = [MACCommand.decode(message.payload.frmpayload)] elif message.hasMACCommands(): commands = message.commands for command in commands: if command.isLinkCheckReq(): self._processLinkCheckReq(device, command, request, rxpk.lsnr) elif command.isLinkADRAns(): self._processLinkADRAns(device, command) # TODO: add other MAC commands # Process application data message if message.isUnconfirmedDataUp() or message.isConfirmedDataUp(): confirmed = message.isConfirmedDataUp() # Find the app app = next( (a for a in self.config.apps if a.appeui == device.appeui), None) if app is None: log.info( "Message from {devaddr} - AppEUI {appeui} " "does not match any configured applications.", devaddr=euiString(device.devaddr), appeui=device.appeui) returnValue(False) # Decrypt frmpayload message.decrypt(device.appskey) appdata = str(message.payload.frmpayload) # Save the device state and route the data to an application # server via the configured interface log.info("Outbound message from devaddr {devaddr}", devaddr=devaddrString(device.devaddr)) self._outboundAppMessage(app, int(device.devaddr), appdata, confirmed)
import argparse import copy import logging.config import config as cfg from device import Device if __name__ == '__main__': # Command-line arguments parser = argparse.ArgumentParser(description='Device boot script') parser.add_argument('name', type=str, help='device name') parser.add_argument('-l', '--loglevel', default='WARNING', help='log level (DEBUG|INFO|WARNING|ERROR|CRITICAL)') args = parser.parse_args() # Logging setup mylogcfg = copy.deepcopy(cfg.LOGCFG) mylogcfg['handlers']['default']['level'] = args.loglevel.upper() mylogcfg['handlers']['file']['filename'] = '/dev/null' logging.config.dictConfig(mylogcfg) log = logging.getLogger('boot_device') name = args.name device = Device(name) log.info('booting device %s...', name) device.start()