def _start_monero_wallet(self): """Run the Monero wallet, which connects to the daemon""" if self._wallet_rpc_loaded(): logger.info('XMR Wallet already loaded!') return command = [ self.wallet_bin_path, '--trusted-daemon', # We trust our own daemon. If you use a different daemon, remove this '--daemon-address', self.daemon_address, '--rpc-bind-port={}'.format(self.rpcport), '--wallet-file', os.path.join(self.datadir, 'wallets', self.wallet_filename), '--disable-rpc-login', '--prompt-for-password' ] logger.info("Starting XMR wallet: {}".format(' '.join(command))) wallet_proc = popen_spawn.PopenSpawn(command) logger.info("Sending password") wallet_proc.sendline(self.wallet_password) logger.info("Sent password") wait_for_success(self._wallet_rpc_loaded, 'Wallet RPC')
def popen_spawn(self, cmd, timeout: Optional[timedelta] = timedelta(seconds=30), maxread: int = 2000, searchwindowsize: Optional[int] = None, logfile: Optional[IO] = None, cwd: Optional[str] = None, env: Optional[Mapping[str, str]] = None, encoding: Optional[str] = 'utf-8', codec_errors: Any = 'strict', preexec_fn: Optional[Callable[[], Any]] = None): '''Provides an interface like `Spawn` keyword using subprocess.Popen.''' encoding = self._optional_arg_conversion(encoding) timeout = self._timearg_to_seconds(timeout) return self._spawn( lambda: popen_spawn.PopenSpawn(cmd=cmd, timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize, logfile=logfile, cwd=cwd, env=env, encoding=encoding, codec_errors=codec_errors, preexec_fn=preexec_fn))
def __init__(self, server_args='', log_file=None, zmq_in_port=7000, zmq_out_port=7001): super(StdioLanguageServerClient, self).__init__(zmq_in_port, zmq_out_port) self.req_status = {} self.process = None logger.debug(repr(server_args)) logger.debug('Environment variables: {0}'.format( list(os.environ.keys()))) if log_file: logger.debug('Redirect stderr to {0}'.format(log_file)) log_file_handle = open(log_file, 'wb') else: log_file_handle = None self.process = popen_spawn.PopenSpawn(server_args, logfile=log_file_handle) logger.info('Process pid: {0}'.format(self.process.pid)) logger.info('Connecting to language server on stdio') super(StdioLanguageServerClient, self).finalize_initialization() self.reading_thread = StdioIncomingMessageThread() self.reading_thread.initialize(self.process, self.zmq_out_socket, self.req_status, expectable=True)
def darknet(message): os.chdir("C:/Users/NAME/Desktop/darknet-master/build/darknet/x64") process = popen_spawn.PopenSpawn('darknet.exe detector test data/obj.data \ yolov3-tiny-obj.cfg yolov3-tiny-obj_X.weights \ -dont_show -ext_output -save_labels') #Running Darknet print(message) return process
def setUp(self): if platform.system() == "Windows": print("\nStart mosquitto broker") broker_path = os.path.join(curpath, "..\\MQTTBroker\\mosquitto.exe") print(broker_path) self.assertTrue(os.path.isfile(broker_path)) self.c = popen_spawn.PopenSpawn(broker_path) # create a new mqtt broker client = mqtt.Client() ################################## # Create a sample MQTT Publisher ################################## self.aMazePublisher = Sample_MQTT_Publisher(client) ################################## # Create a sample MQTT Subscriber ################################## self.aMazeSubscriber = Sample_MQTT_Subscriber(client) # start the mqtt broker client.loop_start() time.sleep(0.1)
def spawn_as_user(self, cmd, timeout=10): """Run pexpect as the user spawning the notebook This method attaches kerberos credentals to the command env if they exist. """ user = pwd.getpwnam(self.user.name) uid = user.pw_uid env = os.environ krb_files = glob("/tmp/krb5cc_{uid}*".format(uid=uid)) if krb_files: env["KRB5CCNAME"] = max(krb_files, key=os.path.getctime) popen_kwargs = dict( env=env, timeout=timeout, encoding="utf-8", preexec_fn=self.make_preexec_fn(self.user.name) ) self.log.debug("Running: {cmd} as {user}".format( cmd=cmd, user=self.user.name)) return popen_spawn.PopenSpawn(cmd, **popen_kwargs)
def login(self, fileJsonConfigure, intMinimumReadings, intMinimumHits, intTimeout): # command_0 = [r"..\tools\bin\win32\vrtrackingcalib.exe", r"/usedisambiguation", "framer", \ # r"/bodycal", fileJsonConfigure, intMinimumReadings, intMinimumHits] # result = subprocess.Popen(command_0, shell = False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None) # print result.stdout.readlines() command_0 = r"..\tools\bin\win32\vrtrackingcalib.exe /usedisambiguation framer /bodycal " +\ fileJsonConfigure + ' ' + str(intMinimumReadings) + ' ' + str(intMinimumHits) print command_0 ##r"..\tools\bin\win32\vrtrackingcalib.exe /usedisambiguation framer /bodycal imu_updated.json 800 200 " self.consoleHandler = ps.PopenSpawn(command_0, timeout=int(intTimeout) * 60) index = self.consoleHandler.expect(["Ready to run capture position number 0", \ "Error connecting or Lighthouse IMU", \ pexpect.EOF, \ pexpect.TIMEOUT]) if index == 0: strResult = self.consoleHandler.before serial_pattern = "Attempting HID Open IMU:\s+(\w+-.*)" strSerial = re.search(serial_pattern, strResult) print "strSerial", strSerial self.serialNum = strSerial.group(1) print "\n%s\n" % self.serialNum logging.log(logging.INFO, strResult) return True else: return False
def spawn_jl_process(self): self.julia_process = popen_spawn.PopenSpawn( 'julia --project=project_files/pomato', cwd=self.wdir, timeout=100000, logfile=FileAdapter(self.logger)) self.julia_process.sendline('include("code_jl/main.jl")') self.julia_process.expect(["Initialized", "ERROR"])
def run_fstlexicon(self): if FSTFeature.lexicon is not None: return dir = os.path.dirname(os.path.realpath(__file__)) jar_file = os.path.join(dir, 'fstlexicon.jar').replace('\\', '/') process: PopenSpawn = popen_spawn.PopenSpawn('java -jar %s' % (jar_file, ), encoding='utf-8') FSTFeature.lexicon: PopenSpawn = process
def _open_cmd_logon(): child = popen_spawn.PopenSpawn('cmd') child.sendline( f"tacmd login -s {rtes[rte]['hostname']}:{rtes[rte]['tems_http']} -u {username} -p {password}" ) child.expect(f'KUIC00007I: User {username} logged into server') child.expect(command_prompt) return child
def __run_analyzer(self) -> PopenSpawn: dir = os.path.dirname(os.path.realpath(__file__)) jar = os.path.join(dir, "polish-simple-analyzer.jar").replace('\\', '/') self.__download_analyzer(jar) process: PopenSpawn = popen_spawn.PopenSpawn('java -jar %s' % (jar, ), encoding='utf-8') return process
def call(): '''Realiza llamadas a codigo de red neuronal en C y pasa datos a codigo path.py''' child = popen_spawn.PopenSpawn('./a.out') child.expect('Hello .*') print(child.after.decode("utf-8"), end='') child.expect('.*') print(child.after.decode("utf-8"), end='') print(receive([1, 2, 3, 4, 5]))
def spawn_snapcraft(self, command: Union[str, List[str]]): snapcraft_command = self.snapcraft_command if isinstance(snapcraft_command, str): snapcraft_command = [snapcraft_command] try: return popen_spawn.PopenSpawn(" ".join(snapcraft_command + command)) except FileNotFoundError: self.addDetail("command", content.text_content(str(snapcraft_command)))
def with_cloud_sql_proxy(self, project_id: str, instance_name: str, cloud_sql_proxy_path: Optional[str] = None, region: str = 'us-west1', port: int = 5432): """A context manager to run and kill cloud sql proxy subprocesses. Used to provides secure access to your Cloud SQL Second Generation instances without having to whitelist IP addresses or configure SSL. For more information: https://cloud.google.com/sql/docs/postgres/sql-proxy Args: project_id: GCP project id. instance_name: Name of the Cloud SQL instance cloud sql proxy targets at. cloud_sql_proxy_path: The command to run your cloud sql proxy. region: Where the Cloud SQL instance is in. port: The port your Postgres database is using. By default it is 5432. Yields: None Raises: DatabaseError: If cloud sql proxy failed to start after 5 seconds. """ try: db.close_old_connections() except django.core.exceptions.ImproperlyConfigured: # The Django environment is not correctly setup. This might be # because we are calling Django management commands with subprocess # calls. In this case the subprocess we are calling will handle # closing of old connections. pass instance_connection_string = '{0}:{1}:{2}'.format( project_id, region, instance_name) instance_flag = '-instances={}=tcp:{}'.format( instance_connection_string, port) if cloud_sql_proxy_path is None: cloud_sql_proxy_path = shutil.which('cloud_sql_proxy') assert cloud_sql_proxy_path, 'could not find cloud_sql_proxy_path' process = popen_spawn.PopenSpawn([cloud_sql_proxy_path, instance_flag]) try: # Make sure cloud sql proxy is started before doing the real work process.expect('Ready for new connections', timeout=60) yield except pexpect.exceptions.TIMEOUT: raise DatabaseError(( 'Cloud SQL Proxy was unable to start after 60 seconds. Output ' 'of cloud_sql_proxy: \n{}').format(process.before)) except pexpect.exceptions.EOF: raise DatabaseError( ('Cloud SQL Proxy exited unexpectedly. Output of ' 'cloud_sql_proxy: \n{}').format(process.before)) finally: process.kill(signal.SIGTERM)
def main(): cmd = "go run main.go" child = p.PopenSpawn(cmd) child.logfile = Logger(cmd) child.expect("Enter text:") child.sendline("Coool kids") child.expect("Favourite color") # This appears to be the culprit line child.sendline("") child.expect("Response: red") print("Done")
def __init__(self): """Main terminal handler constructor.""" self.os = os.name if self.os == WINDOWS: self.cmd = 'cmd' self.pty_fork = lambda x: pspawn.PopenSpawn(x, encoding="utf-8") else: self.cmd = '/usr/bin/env bash' self.pty_fork = pexpect.spawnu self.sockets = {} self.consoles = {}
def _spawn_helper(n, cmd, interpreter=[]): global _children, _logs name = os.path.basename(cmd[0]) log_name = 'out/{}{:03d}.log'.format(name, n) log = open(log_name, 'wb') log.write('=============================\n{}{} {}\n'.format(name, n, ' '.join(cmd[1:])).encode()) log.write('=============================\n'.encode()) child = popen_spawn.PopenSpawn(interpreter + cmd, env=_spawn_env(), logfile=log) child.linesep = os.linesep _children.append(child) _logs.append(log) return child
def download(self, deviceName, target=None): dut = self.configDut[deviceName] if 'download' not in dut: raise AssertionError('Download method is not configured for {}'.format(deviceName)) for d in dut['download']: if len(d) <= 1: print('download tool {} is not supported yet'.format(d['tool'] if 'tool' in d else d)) continue if d['tool'].upper() == 'MDK': if os.name != 'nt': print('MDK is only supported on Windows') continue cmd = [d['path'], '-f', str(Path(d['workdir']) / d['project']), '-t', d['target']] subprocess.run(cmd, check=True) break if d['tool'].upper() == 'JLINK': cmd = [d['path'], '-device', d['device'], '-if', d['interface'], '-speed', str(d['speed']), '-autoconnect', '1'] if os.name == 'nt': from pexpect import popen_spawn a = popen_spawn.PopenSpawn(' '.join(cmd), encoding='utf-8') elif os.name == 'posix': a = pexpect.spawn(' '.join(cmd), encoding='utf-8') else: raise AssertionError('Not supported OS {}'.format(os.name)) try: a.expect_exact('J-Link>', timeout=5) except: a.kill(9) raise AssertionError('J-Link running failed') if os.path.isabs(d['datafile']): data_file = Path(d['datafile']) else: data_file = Path(self.config["resource_dir"]) / d['datafile'] cmds = ['r', 'exec EnableEraseAllFlashBanks', 'erase', 'loadbin {} {:x} SWDSelect'.format(data_file, d['flash_addr']), 'verifybin {} {:x}'.format(data_file, d['flash_addr']), 'r', 'g'] for c in cmds: a.sendline(c) idx = a.expect_list([re.compile('J-Link>'), re.compile('failed'), pexpect.TIMEOUT], timeout=120, searchwindowsize=10) if idx != 0: a.kill(9) raise AssertionError('JLink command "{}" failed:\n{}\n{}'.format(c, a.before, a.after)) a.sendline('qc') a.expect(pexpect.EOF) break print('Firmware downloading failed by {}, try next tool...'.format(d['tool'].upper())) else: raise AssertionError('Downloading firmware for {} failed'.format(deviceName))
def __init__(self, prog): assert isinstance(prog, str) self.dbg = popen_spawn.PopenSpawn("radare2 " + prog) self.dbg.sendline("e scr.color = false") self.dbg.sendline("e scr.utf8 = false") self.dbg.sendline("ood") self.dbg.sendline("aa") self.breakpoints = set() self.breakpoint_map = {} match = self.dbg.expect([TIMEOUT, r'.*\[(?:0x[a-f0-9]+)\]>.*']) if not match: raise ValueError("invalid input received on __init__")
async def startServer(message): global serverProcess global serverStatus serverStatus = starting serverProcess = popen_spawn.PopenSpawn(command) await client.change_presence(status=discord.Status.idle, activity=discord.Game("Tekxit STARTING")) threading.Thread(target=serverThread, daemon=True, args=( message, serverProcess, )).start()
def __init__(self, server_args='', log_file='', zmq_in_port=7000, zmq_out_port=7001): super(StdioLanguageServerClient, self).__init__( zmq_in_port, zmq_out_port) self.req_status = {} self.process = None logger.debug(server_args) logger.debug('Redirect stderr to {0}'.format(log_file)) self.process = popen_spawn.PopenSpawn(server_args) logger.info('Connecting to language server on stdio') super(StdioLanguageServerClient, self).finalize_initialization() self.reading_thread = StdioIncomingMessageThread() self.reading_thread.initialize(self.process, self.zmq_out_socket, self.req_status, expectable=True)
def get_pexpect_child(): if os.name == 'nt': from pexpect import popen_spawn shell = 'cmd.exe' child = popen_spawn.PopenSpawn(shell) child.expect('>') child.sendline('chcp 65001') child.expect(LINE_END) elif os.name == 'posix': shell = '/bin/bash' child = pexpect.spawn(shell) #child.logfile = sys.stdout.buffer return child
def add_docs_html(self): """ Makes the html documentation. """ ps = pops.PopenSpawn('powershell', timeout = 3) ps.expect('>') ps.sendline('cd {}'.format(self.docs_path)) ps.expect('>') ps.sendline('make html') ps.expect('>') ps.sendline('dir') self.logger.logger.info( f'The html documentation has been generated' )
def __init__(self, wdir, logger, julia_model): self.julia_process = popen_spawn.PopenSpawn( 'julia --project=project_files/pomato', cwd=wdir, timeout=100000, logfile=FileAdapter(logger)) self.logger = logger self.solved = False if julia_model == "market_model": self.julia_process.sendline('using MarketModel') self.julia_process.expect(["Initialized", "ERROR"]) elif julia_model == "cbco": self.julia_process.sendline('using RedundancyRemoval') self.julia_process.expect(["Initialized", "ERROR"]) else: self.logger.error("Model Options not available!")
def login(self): command_0 = [r"..\tools\bin\win32\imu_calibrator.exe"] self.consoleHandler = ps.PopenSpawn( r"..\tools\bin\win32\imu_calibrator.exe") index = self.consoleHandler.expect(["Lighthouse VrController HID opened", \ "Error connecting or Lighthouse IMU", \ pexpect.EOF, \ pexpect.TIMEOUT]) if index == 0: strResult = self.consoleHandler.before serial_pattern = "Attempting HID Open IMU:\s+(\w+-.*)" strSerial = re.search(serial_pattern, strResult) print "strSerial", strSerial self.serialNum = strSerial.group(1) print "\n%s\n" % self.serialNum logging.log(logging.INFO, strResult) return True else: return False
def login(self): self.consoleHandler = ps.PopenSpawn( r"..\tools\bin\win32\lighthouse_console.exe") index = self.consoleHandler.expect(["Lighthouse VrController HID opened", \ "No connected lighthouse device found", \ pexpect.EOF, \ pexpect.TIMEOUT]) if index == 0: strResult = self.consoleHandler.before serial_pattern = "lighthouse_console: Connected to receiver\s+(\w+-.*)" strSerial = re.search(serial_pattern, strResult) print "strSerial", strSerial self.serialNum = (strSerial.group(1)).strip("\r") print "\n%s\n" % self.serialNum logging.log(logging.INFO, strResult) return True else: return False
def __init__(self, **kwargs): super().__init__(**kwargs) # initializing purescript project with pulp # this project will be shared among all kernels project_path = os.path.join(os.path.dirname(__file__), 'temp') try: os.makedirs(project_path) except OSError as err: if err.errno != errno.EEXIST: raise exec_str = 'pulp.cmd' if sys.platform == 'win32' else 'pulp' subprocess.run([exec_str, 'init'], cwd=project_path) self.child = popen_spawn.PopenSpawn(exec_str + ' repl', cwd=project_path) self.child.expect('\n> ')
def update_ip(): cmd = "git add ." subprocess.call(cmd, shell=True) cmd = 'git commit -m "system update"' subprocess.call(cmd, shell=True) #cmd = "git remote set-url origin https://github.com/Tehsurfer/git-test.git" #subprocess.call(cmd, shell=True) cmd = "git push " child_process = popen_spawn.PopenSpawn(cmd) child_process.expect('User') child_process.sendline(user) child_process.expect('Password') child_process.sendline(password) #print('returned value:', returned_value) print('end of commands')
def run_cloud_sql_proxy(cloud_sql_proxy_path): instance_flag = '-instances={}=tcp:{}'.format(INSTANCE_CONNECTION_NAME, PORT) if cloud_sql_proxy_path is None: assert cloud_sql_proxy_path, 'Could not find cloud_sql_proxy path' process = popen_spawn.PopenSpawn([cloud_sql_proxy_path, instance_flag]) try: process.expect('Ready for new connection', timeout=5) yield except pexpect.exceptions.TIMEOUT: raise ConnectionError( ('Cloud SQL Proxy was unable to start after 5 seconds. Output ' 'of cloud_sql_proxy: \n{}').format(process.before)) except pexpect.exceptions.EOF: raise ConnectionError( ('Cloud SQL Proxy exited unexpectedly. Output of ' 'cloud_sql_proxy: \n{}').format(process.before)) finally: process.kill(signal.SIGTERM)
def displayAndStartProgress(self, cmd): thread = popen_spawn.PopenSpawn(cmd) # 比對ffmpeg output的資料 # 參考自:https://stackoverflow.com/questions/7632589/getting-realtime-output-from-ffmpeg-to-be-used-in-progress-bar-pyqt4-stdout cpl = thread.compile_pattern_list([EOF, "time= *\d+:\d+:\d+"]) while True: i = thread.expect_list(cpl, timeout=None) if i == 0: # EOF print("the sub process exited") break elif i == 1: time_number = thread.match.group(0) time_number = time_number[5:].decode('utf-8') current_second = float(time_number[:2]) * 60 * 60 + float( time_number[3:5]) * 60 + float(time_number[6:]) percent = current_second / globalVariable.media_length * 100 # print(current_second, globalVariable.media_length) self.transform_progress.emit(percent)