當前位置: 首頁>>代碼示例>>Python>>正文


Python sarge.run方法代碼示例

本文整理匯總了Python中sarge.run方法的典型用法代碼示例。如果您正苦於以下問題:Python sarge.run方法的具體用法?Python sarge.run怎麽用?Python sarge.run使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在sarge的用法示例。


在下文中一共展示了sarge.run方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: startHotspot

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def startHotspot(self):
		with self._startHotspotCondition:
			isHotspotActive = self.isHotspotActive()

			if isHotspotActive is None: # this means is not possible in this system
				return "Hotspot is not possible on this system"

			if isHotspotActive is True:
				return True

			try:
				p = sarge.run("service wifi_access_point start", stderr=sarge.Capture())
				if p.returncode != 0:
					returncode = p.returncode
					stderr_text = p.stderr.text
					logger.warn("Start hotspot failed with return code %i: %s" % (returncode, stderr_text))
					return "Start hotspot failed with return code %i: %s" % (returncode, stderr_text)
				else:
					return True

			except Exception, e:
				logger.warn("Start hotspot failed with return code: %s" % e)
				return "Start hotspot failed with return code: %s" % e 
開發者ID:AstroPrint,項目名稱:AstroBox,代碼行數:25,代碼來源:debian.py

示例2: _mountPartition

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def _mountPartition(self, partition, directory):
		if directory:
			try:
				if not os.path.exists(directory):
					os.makedirs(directory)

				p = sarge.run("mount -o iocharset=utf8 %s '%s'" % (partition, directory), stderr=sarge.Capture())
				if p.returncode != 0:
					returncode = p.returncode
					stderr_text = p.stderr.text
					self._logger.warn("Partition mount failed with return code %i: %s" % (returncode, stderr_text))
					return False

				else:
					self._logger.info("Partition %s mounted on %s" % (partition, directory))
					return True

			except Exception, e:
				self._logger.warn("Mount failed: %s" % e)
				return False 
開發者ID:AstroPrint,項目名稱:AstroBox,代碼行數:22,代碼來源:linux.py

示例3: _umountPartition

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def _umountPartition(self, directory):
		if directory:
			try:
				if os.path.exists(directory):
					p = sarge.run("umount '%s'" % directory, stderr=sarge.Capture())
					if p.returncode != 0:
						returncode = p.returncode
						stderr_text = p.stderr.text
						self._logger.warn("Partition umount failed with return code %i: %s" % (returncode, stderr_text))
						return False

					else:
						os.rmdir(directory)
						os.rmdir('/'.join(directory.split('/')[:-1])) #uuid dir
						self._logger.info("Partition umounted from %s" % directory)
						return True

				else:
					return True

			except Exception, e:
				self._logger.warn("umount failed: %s" % e)
				return False 
開發者ID:AstroPrint,項目名稱:AstroBox,代碼行數:25,代碼來源:linux.py

示例4: run_test

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def run_test(command, *checks):
    """Execute a command in a sub-process then check that the output matches some criterion."""
    global env, DEBUG

    if callable(command):
        command = command(env)
    p = run(command)
    if DEBUG:
        print(p.stdout.text)
    if assert_return_code not in checks:
        assert_return_code(p, 0)
    for check, checkarg in pairs(checks):
        if callable(checkarg):
            checkarg = checkarg(env)
        check(p, checkarg)
    label = get_label(p)
    if label is not None:
        env["labels"].append(label)
        print("label is", label) 
開發者ID:open-research,項目名稱:sumatra,代碼行數:21,代碼來源:utils.py

示例5: run_forever

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def run_forever(self):
        webcam_server_app = flask.Flask('webcam_server')

        @webcam_server_app.route('/')
        def webcam():
            action = flask.request.args['action']
            if action == 'snapshot':
                return self.get_snapshot()
            else:
                return self.get_mjpeg()

        webcam_server_app.run(host='0.0.0.0', port=8080, threaded=True) 
開發者ID:kennethjiang,項目名稱:OctoPrint-Anywhere,代碼行數:14,代碼來源:h264_stream.py

示例6: __init_camera__

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def __init_camera__(self, plugin, dev_settings):

        def resolution_tuple(dev_settings):
            res_map = {
                    "low": (320,240),
                    "medium": (640, 480),
                    "high": (1296, 972),
                    "high_16_9": (1280, 720),
                    "ultrahigh_16_9": (1920, 1080),
                    }
            resolution = res_map[dev_settings.get('camResolution', 'medium')]

            return reversed(resolution) if dev_settings.get('rotate90', False) ^ dev_settings.get('rotate90N', False) else resolution   # need to swap width and height if rotated

        if not pi_version():
            self.camera = StubCamera()
            global FFMPEG
            FFMPEG = 'ffmpeg'
        else:
            sarge.run('sudo service webcamd stop')

            try:
                import picamera
                self.camera = picamera.PiCamera()
                self.camera.framerate=25
                self.camera.resolution=resolution_tuple(dev_settings)
                self.camera.hflip=dev_settings.get('flipH', False)
                self.camera.vflip=dev_settings.get('flipV', False)

                rotation = (90 if dev_settings.get('rotate90', False) else 0)
                rotation += (-90 if dev_settings.get('rotate90N', False) else 0)
                self.camera.rotation=rotation
            except:
                sarge.run('sudo service webcamd start')   # failed to start picamera. falling back to mjpeg-streamer
                plugin.config.set_picamera_error(True)
                self.sentryClient.captureException()
                exc_type, exc_obj, exc_tb = sys.exc_info()
                _logger.error(exc_obj, exc_info=True)
                return False
        return True 
開發者ID:kennethjiang,項目名稱:OctoPrint-Anywhere,代碼行數:42,代碼來源:h264_stream.py

示例7: start_server

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def start_server():
        app.run(host='0.0.0.0', port=3333, threaded=False) 
開發者ID:kennethjiang,項目名稱:OctoPrint-Anywhere,代碼行數:4,代碼來源:h264_stream.py

示例8: afterApiRequests

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def afterApiRequests(resp):

	# Allow crossdomain
	allowCrossOrigin = s().getBoolean(["api", "allowCrossOrigin"])
	if request.method != 'OPTIONS' and 'Origin' in request.headers and allowCrossOrigin:
		resp.headers['Access-Control-Allow-Origin'] = request.headers['Origin']

	return resp


#~~ first run setup


# @api.route("/setup", methods=["POST"])
# def firstRunSetup():
# 	if not s().getBoolean(["server", "firstRun"]):
# 		abort(403)

# 	if "ac" in request.values.keys() and request.values["ac"] in valid_boolean_trues and \
# 					"user" in request.values.keys() and "pass1" in request.values.keys() and \
# 					"pass2" in request.values.keys() and request.values["pass1"] == request.values["pass2"]:
# 		# configure access control
# 		s().setBoolean(["accessControl", "enabled"], True)
# 		octoprint.server.userManager.addUser(request.values["user"], request.values["pass1"], True, ["user", "admin"])
# 		s().setBoolean(["server", "firstRun"], False)
# 	elif "ac" in request.values.keys() and not request.values["ac"] in valid_boolean_trues:
# 		# disable access control
# 		s().setBoolean(["accessControl", "enabled"], False)
# 		s().setBoolean(["server", "firstRun"], False)

# 		octoprint.server.loginManager.anonymous_user = astroprint.users.DummyUser
# 		octoprint.server.principals.identity_loaders.appendleft(astroprint.users.dummy_identity_loader)

# 	s().save()
# 	return NO_CONTENT

#~~ system state 
開發者ID:AstroPrint,項目名稱:AstroBox,代碼行數:39,代碼來源:__init__.py

示例9: performSystemAction

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def performSystemAction(self,action,sendResponse):
		available_actions = settings().get(["system", "actions"])
		logger = logging.getLogger(__name__)

		for availableAction in available_actions:
			if availableAction["action"] == action:
				command = availableAction["command"]
				if command:
					logger.info("Performing command: %s" % command)

					def executeCommand(command, logger):
						time.sleep(0.5) #add a small delay to make sure the response is sent
						try:
							p = sarge.run(command, stderr=sarge.Capture())
							if p.returncode != 0:
								returncode = p.returncode
								stderr_text = p.stderr.text
								logger.warn("Command failed with return code %i: %s" % (returncode, stderr_text))
								sendResponse({'success': False})
							else:
								logger.info("Command executed sucessfully")
								sendResponse({'success': True})

						except Exception, e:
							logger.warn("Command failed: %s" % e)

					executeThread = threading.Thread(target=executeCommand, args=(command, logger))
					executeThread.start()

				else:
					logger.warn("Action %s is misconfigured" % action)
					sendResponse('action_not_configured', True)

				return 
開發者ID:AstroPrint,項目名稱:AstroBox,代碼行數:36,代碼來源:system.py

示例10: run

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def run(self):
		self._stopped = False
		self._loop = GObject.MainLoop()

		self._propertiesListener = NetworkManager.NetworkManager.OnPropertiesChanged(self.propertiesChanged)
		self._stateChangeListener = NetworkManager.NetworkManager.OnStateChanged(self.globalStateChanged)

		connectionState = NetworkManager.NetworkManager.State
		logger.info('Network Manager reports state: *[%s]*' % NetworkManager.const('state', connectionState))
		if connectionState == NetworkManager.NM_STATE_CONNECTED_GLOBAL:
			self._setOnline(True)

		#d = self.getActiveConnectionDevice()
		#if d:
		#	self._devicePropertiesListener = d.Dhcp4Config.connect_to_signal('PropertiesChanged', self.activeDeviceConfigChanged)
		#	self._currentIpv4Address = d.Ip4Address
		#	self._activeDevice = d
		#	self._online = True
		#	logger.info('Active Connection found at %s (%s)' % (d.IpInterface, d.Ip4Address))

		while not self._stopped:
			try:
				self._loop.run()

			except KeyboardInterrupt:
				#kill the main process too
				from octoprint import astrobox
				astrobox.stop()

			except DBusException as e:
				#GObject.idle_add(logger.error, 'Exception during NetworkManagerEvents: %s' % e)
				logger.error('Exception during NetworkManagerEvents: %s' % e)

			finally:
				self.stop() 
開發者ID:AstroPrint,項目名稱:AstroBox,代碼行數:37,代碼來源:debian.py

示例11: _process_snapshot

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def _process_snapshot(self, snapshot_path, pixfmt="yuv420p"):
		hflip  = self._settings.global_get_boolean(["webcam", "flipH"])
		vflip  = self._settings.global_get_boolean(["webcam", "flipV"])
		rotate = self._settings.global_get_boolean(["webcam", "rotate90"])
		ffmpeg = self._settings.global_get(["webcam", "ffmpeg"])
		
		if not ffmpeg or not os.access(ffmpeg, os.X_OK) or (not vflip and not hflip and not rotate):
			return

		ffmpeg_command = [ffmpeg, "-y", "-i", snapshot_path]

		rotate_params = ["format={}".format(pixfmt)] # workaround for foosel/OctoPrint#1317
		if rotate:
			rotate_params.append("transpose=2") # 90 degrees counter clockwise
		if hflip:
			rotate_params.append("hflip") 		# horizontal flip
		if vflip:
			rotate_params.append("vflip")		# vertical flip

		ffmpeg_command += ["-vf", sarge.shell_quote(",".join(rotate_params)), snapshot_path]
		self._logger.info("Running: {}".format(" ".join(ffmpeg_command)))

		p = sarge.run(ffmpeg_command, stdout=sarge.Capture(), stderr=sarge.Capture())
		if p.returncode == 0:
			self._logger.info("Rotated/flipped image with ffmpeg")
		else:
			self._logger.warn("Failed to rotate/flip image with ffmpeg, "
			                  "got return code {}: {}, {}".format(p.returncode,
			                                                      p.stdout.text,
			                                                      p.stderr.text)) 
開發者ID:OctoPrint,項目名稱:OctoPrint-Pushbullet,代碼行數:32,代碼來源:__init__.py

示例12: deauth

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def deauth(bssid=None, client=None, channel=None, packets=0, state=None):
    client_arg = '-c %s' % client if client is not None else ''

    feeder = Feeder()
    cmd_dump = '/usr/sbin/airodump-ng --channel %d -w /home/dusan/deauth %s >/dev/null 2>/dev/null ' % (channel, IFACE)
    print '++++ cmd: %s' % cmd_dump

    p = run(cmd_dump, async=True)

    try:
        while len(p.commands) == 0:
            time.sleep(0.15)

        # if state['last'] != channel:
        #     cmd_airmon = 'iwconfig %s channel %s' % (IFACE, channel)
        #     print '++++ cmd: %s' % cmd_airmon
        #     p = subprocess.Popen(cmd_airmon, shell=True)
        #     p.communicate()
        #     state['last'] = channel

        cmd = '/usr/sbin/aireplay-ng -0 %d -D -a %s %s %s' % (packets, bssid, client_arg, IFACE)
        print '++++ cmd: %s' % cmd

        #time.sleep(3)
        #return 0

        p2 = subprocess.Popen(cmd, shell=True)
        p2.communicate()

        time.sleep(10)
        p.commands[0].terminate()
        time.sleep(1)
        p.commands[0].kill()

    except Exception as e:
        traceback.print_exc()
    finally:
        feeder.close()
        print '++++ END'
    pass 
開發者ID:ph4r05,項目名稱:kismet-deauth-wpa2-handshake-plugin,代碼行數:42,代碼來源:runclient.py

示例13: check_soc_temp

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def check_soc_temp(self):
        if self.debugMode:
            import random
            return str(round(random.uniform(5, 60), 2))

        if self.is_supported:
            from sarge import run, Capture

            p = run(self.temp_cmd, stdout=Capture())
            if p.returncode == 1:
                self.is_supported = False
                self._logger.debug("SoC temperature not found.")
            else:
                p = p.stdout.text

            self._logger.debug("response from sarge: %s" % p)
            self._logger.debug("used pattern: %r" % self.parse_pattern)
            match = re.search(self.parse_pattern, p)
            temp = 0
            if not match:
                self._logger.debug("match: not found")
                self.is_supported = False
            else:
                temp = self.parse_temperature(match)
                self._logger.debug("match: %s" % str(temp))

            return temp

        return 0 
開發者ID:imrahil,項目名稱:OctoPrint-NavbarTemp,代碼行數:31,代碼來源:sbc.py

示例14: run

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def run(command):
    """Run a command in the Sumatra project directory and capture the output."""
    return sarge.run(command, cwd=working_dir, stdout=sarge.Capture(timeout=10, buffer_size=1)) 
開發者ID:open-research,項目名稱:sumatra,代碼行數:5,代碼來源:utils.py

示例15: get_label

# 需要導入模塊: import sarge [as 別名]
# 或者: from sarge import run [as 別名]
def get_label(p):
    """Obtain the label generated by 'smt run'."""
    match = label_pattern.search(p.stdout.text)
    if match is not None:
        return match.groupdict()["label"]
    else:
        return None 
開發者ID:open-research,項目名稱:sumatra,代碼行數:9,代碼來源:utils.py


注:本文中的sarge.run方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。