我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.execv()。
def _RunGdb(device, package_name, output_directory, target_cpu, extra_args, verbose): gdb_script_path = os.path.dirname(__file__) + '/adb_gdb' cmd = [ gdb_script_path, '--package-name=%s' % package_name, '--output-directory=%s' % output_directory, '--adb=%s' % adb_wrapper.AdbWrapper.GetAdbPath(), '--device=%s' % device.serial, # Use one lib dir per device so that changing between devices does require # refetching the device libs. '--pull-libs-dir=/tmp/adb-gdb-libs-%s' % device.serial, ] # Enable verbose output of adb_gdb if it's set for this script. if verbose: cmd.append('--verbose') if target_cpu: cmd.append('--target-arch=%s' % _TargetCpuToTargetArch(target_cpu)) cmd.extend(extra_args) logging.warning('Running: %s', ' '.join(pipes.quote(x) for x in cmd)) print _Colorize('YELLOW', 'All subsequent output is from adb_gdb script.') os.execv(gdb_script_path, cmd)
def _RunShell(devices, package_name, cmd): if cmd: parallel_devices = device_utils.DeviceUtils.parallel(devices) outputs = parallel_devices.RunShellCommand( cmd, run_as=package_name).pGet(None) for output in _PrintPerDeviceOutput(devices, outputs): for line in output: print line else: adb_path = adb_wrapper.AdbWrapper.GetAdbPath() cmd = [adb_path, '-s', devices[0].serial, 'shell'] # Pre-N devices do not support -t flag. if devices[0].build_version_sdk >= version_codes.NOUGAT: cmd += ['-t', 'run-as', package_name] else: print 'Upon entering the shell, run:' print 'run-as', package_name print os.execv(adb_path, cmd)
def updateCheck(): from pathlib import Path if not shutil.which("git"): return # check if new commits are available projectDir = str(Path(__file__).parent) subprocess.call(["git", "fetch"], cwd=projectDir) output = subprocess.check_output(["git", "status", "-uno"], cwd=projectDir) behindIndex = output.find(b"Your branch is behind ") if behindIndex > 0: msgEnd = output.find(b"\n (use \"git pull\" to update your local branch)") if msgEnd > 0: output = output[behindIndex:msgEnd] statusUpdate("Current CheriBuild checkout can be updated: ", output.decode("utf-8")) if input("Would you like to update before continuing? y/[n] (Enter to skip) ").lower().startswith("y"): subprocess.check_call(["git", "pull", "--rebase"], cwd=projectDir) os.execv(sys.argv[0], sys.argv)
def _first_stage(): import os,sys,zlib R,W=os.pipe() r,w=os.pipe() if os.fork(): os.dup2(0,100) os.dup2(R,0) os.dup2(r,101) for f in R,r,W,w:os.close(f) os.environ['ARGV0']=e=sys.executable os.execv(e,['mitogen:CONTEXT_NAME']) os.write(1,'EC0\n') C=zlib.decompress(sys.stdin.read(input())) os.fdopen(W,'w',0).write(C) os.fdopen(w,'w',0).write('%s\n'%len(C)+C) os.write(1,'EC1\n') sys.exit(0)
def seen_sieve(paraml, input=None, db=None, bot=None, notice=None, say=None): if not db_ready: db_init(db, bot) if re.match(r'^(s|S)/.*/.*\S*$', input.msg): correction(input,db,notice,say) return # keep private messages private if input.chan[:1] == "#": #try: db.execute("insert or replace into seen(name, time, quote, chan, host) values(?,?,?,?,?)", (input.nick.lower(), time.time(), input.msg.replace('\"', "").replace("'", ""), input.chan, input.mask)) db.commit() #except: # for botcon in bot.conns: # if inp: # bot.conns[botcon].cmd("QUIT", ["Restarted by {} ({})".format(nick, inp)]) # else: # bot.conns[botcon].cmd("QUIT", ["Restarted by {}.".format(nick)]) # time.sleep(5) # args = sys.argv[:] # args.insert(0, sys.executable) # os.execv(sys.executable, args)
def restartInProcess(self, app): args = sys.argv[:] args.insert(0, sys.executable) apppath = j.system.fs.joinPaths(j.dirs.appDir, app) max_fd = 1024 for fd in range(3, max_fd): try: flags = fcntl.fcntl(fd, fcntl.F_GETFD) except IOError: continue fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC) os.chdir(apppath) os.execv(sys.executable, args) # def getRedisClient(self,appname,actorname): # if ini.checkSection("redis"): # redisip=ini.getValue("redis","ipaddr") # redisport=ini.getValue("redis","port") #redisclient=redis.StrictRedis(host=redisip, port=int(redisport), db=0) # else: # redisclient=None # return redisclient
def restartInProcess(self, app): import fcntl args = sys.argv[:] args.insert(0, sys.executable) apppath = j.system.fs.joinPaths(j.dirs.appDir, app) max_fd = 1024 for fd in range(3, max_fd): try: flags = fcntl.fcntl(fd, fcntl.F_GETFD) except IOError: continue fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC) os.chdir(apppath) os.execv(sys.executable, args)
def exec_in_virtualenv(options): venv = VirtualEnvironment(options) venv.create() venv_python = venv.get_python_program() args = [venv_python, "-m", "performance"] + \ sys.argv[1:] + ["--inside-venv"] # os.execv() is buggy on windows, which is why we use run_cmd/subprocess # on windows. # * https://bugs.python.org/issue19124 # * https://github.com/python/benchmarks/issues/5 if os.name == "nt": venv.run_cmd(args, verbose=False) sys.exit(0) else: os.execv(args[0], args)
def spawnd(path, args, pidfile=None): """ Run a command as a daemon. This method is really just shorthand for the following code: .. python:: daemonize(pidfile=pidfile) _os.execv(path, args) :Parameters: path : str Full path to program to run args : list List of command arguments. The first element in this list must be the command name (i.e., arg0). pidfile : str Path to file to which to write daemon's process ID. The string may contain a ``${pid}`` token, which is replaced with the process ID of the daemon. e.g.: ``/var/run/myserver-${pid}`` """ daemonize(no_close=True, pidfile=pidfile) _os.execv(path, args)
def process_unimported(self): msg = 'Brak modu?u pip!\nNie mo?na zainstalowa?:\n%s' msg_dec = 'Wymagane modu?y:\n{}\nChcesz zainstalowa? (T/n)? ' self.to_import = list(self.unimported) modules_text = '\n'.join([' {} - {}'.format(ins, ver) for _, ins, ver in self.unimported]) if self.try_import('pip', add=False): msg_dec = msg_dec.format(modules_text) decision = Decision(msg_dec, {'T': {self.install_unimported: (self.unimported,)}, 'n': sys.exit}) decision.run() if all(self.import_all(reload=True)): logging.info('...ponowne uruchamianie') os.execv(sys.executable, ['python'] + sys.argv) else: logging.critical('Nie uda?o si? zainstalowa? modu?ów.') raise SystemExit else: logging.critical(msg, modules_text) raise SystemExit
def _set_cloexec(self): """Set the CLOEXEC flag on all open files (except stdin/out/err). If self.max_cloexec_files is an integer (the default), then on platforms which support it, it represents the max open files setting for the operating system. This function will be called just before the process is restarted via os.execv() to prevent open files from persisting into the new process. Set self.max_cloexec_files to 0 to disable this behavior. """ for fd in range(3, self.max_cloexec_files): # skip stdin/out/err try: flags = fcntl.fcntl(fd, fcntl.F_GETFD) except IOError: continue fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
def reExec(self): """ Removes pidfile, registers an exec to happen after shutdown, then stops the reactor. """ self.log.warn("SIGHUP received - restarting") try: self.log.info("Removing pidfile: {log_source.pidfilePath}") os.remove(self.pidfilePath) except OSError: pass self.reactor.addSystemEventTrigger( "after", "shutdown", os.execv, sys.executable, [sys.executable] + sys.argv ) self.reactor.stop()
def test_05_multiapp(self): os.mkdir('webroot') self._writeFiles() self._call_cid(['prepare']) self._call_cid(['build']) pid = os.fork() if not pid: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [self.CIDTEST_BIN, 'devserve']) try: self._testApps() finally: os.kill(pid, signal.SIGTERM) try: os.waitpid(pid, 0) except OSError: pass
def test02_execute(self): pid = os.fork() if not pid: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [self.CIDTEST_BIN, 'service', 'master']) try: res = self._firstGet('http://127.0.0.1:1234/plugin_assets/file.txt') self.assertEqual('STATICFILE', res.text.strip()) res = self._firstGet('http://127.0.0.1:1234/') if res.text.find('redmine') < 0: print(res) self.assertFalse(True) finally: os.kill(pid, signal.SIGTERM) try: os.waitpid(pid, 0) except OSError: pass
def test02_execute(self): return # TODO: pid = os.fork() if not pid: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [self.CIDTEST_BIN, 'service', 'master']) try: res = self._firstGet('http://127.0.0.1:1234/plugin_assets/file.txt') self.assertEqual('STATICFILE', res.text.strip()) res = self._firstGet('http://127.0.0.1:1234/') if res.text.find('redmine') < 0: print(res) self.assertFalse(True) finally: os.kill(pid, signal.SIGTERM) try: os.waitpid(pid, 0) except OSError: pass
def _do_execv(self): """Re-execute the current process. This must be called from the main thread, because certain platforms (OS X) don't allow execv to be called in a child thread very well. """ args = sys.argv[:] self.log('Re-spawning %s' % ' '.join(args)) self._extend_pythonpath(os.environ) if sys.platform[:4] == 'java': from _systemrestart import SystemRestart raise SystemRestart else: args.insert(0, sys.executable) if sys.platform == 'win32': args = ['"%s"' % arg for arg in args] os.chdir(_startup_cwd) if self.max_cloexec_files: self._set_cloexec() os.execv(sys.executable, args)
def from_command(cls, command, before_exec_func=None): """ Create Process from command, e.g. command=['python', '-c', 'print("test")'] :param before_exec_func: Function that is called before `exec` in the process fork. """ assert isinstance(command, list) assert before_exec_func is None or callable(before_exec_func) def execv(): if before_exec_func: before_exec_func() for p in os.environ['PATH'].split(':'): path = os.path.join(p, command[0]) if os.path.exists(path) and os.access(path, os.X_OK): os.execv(path, command) return cls(execv)
def reexec(*cmd, **kwargs): reason = kwargs.pop('reason') assert not kwargs, kwargs print(color('*** exec-ing: {}'.format(reason), '\033[33m')) print(fmt_cmd(cmd)) # Never returns os.execv(cmd[0], cmd)
def reload(): """ Reload process """ try: # Reload and replace current process os.execv(sys.executable, [sys.executable] + sys.argv) except OSError: # Ugh, that failed # Try spawning a new process and exitj os.spawnv( os.P_NOWAIT, sys.executable, [sys.executable] + sys.argv, ) os._exit(os.EX_OK)
def __init__(self, cmd, cwd): self._cmd_return_code = 0 self._cmd_kill_signal = 0 self._shell_pid, self._master_fd = pty.fork() if self._shell_pid == pty.CHILD: os.environ["TERM"] = "linux" os.chdir(cwd) os.execv(cmd[0], cmd)
def run(self): try: scrape_and_extract.scrape_list() except (requests.exceptions.ConnectionError, OSError, IOError): os.execv(sys.executable, [sys.executable] + [os.path.abspath(__file__)])
def start_nginx(nginx, nginx_conf): try: # Control is relinquished to nginx process after this line os.execv(nginx, ['nginx', '-p', '/usr', '-c', nginx_conf]) except OSError as err: logging.error("Failed to launch NGINX: " + nginx) logging.error(err.strerror) sys.exit(3)
def restart(self): self.stop(False) args = ([sys.executable] + ['-W%s' % o for o in sys.warnoptions] + sys.argv) if sys.platform == "win32": args = ['"%s"' % arg for arg in args] os.execv(sys.executable, args)
def launchWithName(name): if name and name != sys.argv[0]: exe = os.path.realpath(sys.executable) log.msg('Changing process name to ' + name) os.execv(exe, [name, sys.argv[0], '--originalname']+sys.argv[1:])
def restart(inp, nick=None, conn=None, bot=None): """restart [reason] -- Restarts the bot with [reason] as its quit message.""" for botcon in bot.conns: if inp: bot.conns[botcon].cmd("QUIT", ["Restarted by {} ({})".format(nick, inp)]) else: bot.conns[botcon].cmd("QUIT", ["Restarted by {}.".format(nick)]) time.sleep(5) #os.execl("./bot", "bot", "restart") args = sys.argv[:] args.insert(0, sys.executable) os.execv(sys.executable, args)
def db_init(db, bot): "check to see that our db has the the seen table and return a connection." try: db.execute("create table if not exists seen(name, time, quote, chan, host, primary key(name, chan))") except: for botcon in bot.conns: bot.conns[botcon].cmd("QUIT", ["Restarted"]) time.sleep(5) #os.execl("./bot", "bot", "restart") args = sys.argv[:] args.insert(0, sys.executable) os.execv(sys.executable, args) db.commit() db_ready = True
def _do_shell(self, args, config): capman = config.pluginmanager.getplugin('capturemanager') if capman: if hasattr(capman, 'suspend_global_capture'): capman.suspend_global_capture(in_=True) else: capman.suspendcapture(in_=True) shell = os.environ.get('SHELL', 'sh') print("Spawning a Unix shell...") with self._run_from_testdir(args): os.execv(shell, [shell] + config.args[1:]) sys.exit(1)
def _menu_restart_pext(self) -> None: # Call _shut_down manually because it isn't called when using os.execv _shut_down(self, self.config_retriever) args = sys.argv[:] args.insert(0, sys.executable) if sys.platform == 'win32': args = ['"%s"' % arg for arg in args] os.chdir(os.getcwd()) os.execv(sys.executable, args)
def _restart(self): await self.bot.shutdown() script = sys.argv[0] if script.startswith(os.getcwd()): script = script[len(os.getcwd()):].lstrip(os.sep) if script.endswith('__main__.py'): args = [sys.executable, '-m', script[:-len('__main__.py')].rstrip(os.sep).replace(os.sep, '.')] else: args = [sys.executable, script] os.execv(sys.executable, args + sys.argv[1:])
def run(self, args, config): pargs = args.pserve_args if not config.filename: print("No config file specified. Must specify a config file.") sys.exit(-1) # unsonic-server is needed to keep the cmdline args for pserve for its # reload option with hupper, otherwise pserve/hupper gets confused. paths = [os.path.abspath( os.path.join(*list(os.path.split(unsonic.CMD)[:-1]) + ["unsonic-server"])), os.path.abspath(os.path.join(os.path.dirname(__file__), "../../", "bin/unsonic-server")), shutil.which("unsonic-server")] for path in paths: if os.access(path, os.X_OK): break else: path = None if not path: print("Failed to find the unsonic-server command.") sys.exit(-1) argv = [path] if len(pargs) and pargs[0] == "--": pargs = pargs[1:] argv.extend(pargs) argv.append(str(config.filename)) print(" ".join(argv)) os.execv(path, argv)
def _execvpe_mockup(defpath=None): """ Stubs out execv and execve functions when used as context manager. Records exec calls. The mock execv and execve functions always raise an exception as they would normally never return. """ # A list of tuples containing (function name, first arg, args) # of calls to execv or execve that have been made. calls = [] def mock_execv(name, *args): calls.append(('execv', name, args)) raise RuntimeError("execv called") def mock_execve(name, *args): calls.append(('execve', name, args)) raise OSError(errno.ENOTDIR, "execve called") try: orig_execv = os.execv orig_execve = os.execve orig_defpath = os.defpath os.execv = mock_execv os.execve = mock_execve if defpath is not None: os.defpath = defpath yield calls finally: os.execv = orig_execv os.execve = orig_execve os.defpath = orig_defpath
def _restart(): os.execv(sys.executable, [sys.executable] + sys.argv) # process = psutil.Process()
def restart_inplace(): """Restarts the bot inplace.""" logger.info('reboot: executable=%s argv=%s', sys.executable, sys.argv) os.execv(sys.executable, [sys.executable] + sys.argv)
def platformExec(self, cmdline): # Basically just like the one in the Ptrace mixin... self.execing = True cmdlist = e_cli.splitargs(cmdline) os.stat(cmdlist[0]) pid = os.fork() if pid == 0: v_posix.ptrace(PT_TRACE_ME, 0, 0, 0) os.execv(cmdlist[0], cmdlist) sys.exit(-1) return pid
def platformExec(self, cmdline): self.execing = True cmdlist = e_cli.splitargs(cmdline) os.stat(cmdlist[0]) pid = os.fork() if pid == 0: ptrace(PT_TRACE_ME, 0, 0, 0) os.execv(cmdlist[0], cmdlist) sys.exit(-1) return pid
def refreshWindow(self): self.btnProcessAgain.setVisible(False) self.btnProcessImage.setVisible(True) self.btnImageBrowse.setEnabled(True) os.execv(sys.executable, ['python'] + sys.argv)
def main_loop(): while True: try: bot.polling(none_stop=True) except Exception as e: print("Exception occurred:", e) break time.sleep(2) os.execv(sys.executable, ['python'] + sys.argv) pass else: break while 1: time.sleep(3)
def took_too_long(): """ Called when :meth:`main` takes too long to run its course (idle timeout before any connection was made). """ timeout_script = os.path.join(APPLICATION_PATH, 'timeout.sh') sys.stdout.flush() # Calling execv() so we can quit the main process to reduce memory usage os.execv('/bin/sh', ['-c', timeout_script]) os._exit(0)
def create_execv(original_name): def new_execv(path, args): """ os.execv(path, args) os.execvp(file, args) """ import os send_process_created_message() return getattr(os, original_name)(path, patch_args(args)) return new_execv
def patch_new_process_functions_with_warning(): monkey_patch_os('execl', create_warn_multiproc) monkey_patch_os('execle', create_warn_multiproc) monkey_patch_os('execlp', create_warn_multiproc) monkey_patch_os('execlpe', create_warn_multiproc) monkey_patch_os('execv', create_warn_multiproc) monkey_patch_os('execve', create_warn_multiproc) monkey_patch_os('execvp', create_warn_multiproc) monkey_patch_os('execvpe', create_warn_multiproc) monkey_patch_os('spawnl', create_warn_multiproc) monkey_patch_os('spawnle', create_warn_multiproc) monkey_patch_os('spawnlp', create_warn_multiproc) monkey_patch_os('spawnlpe', create_warn_multiproc) monkey_patch_os('spawnv', create_warn_multiproc) monkey_patch_os('spawnve', create_warn_multiproc) monkey_patch_os('spawnvp', create_warn_multiproc) monkey_patch_os('spawnvpe', create_warn_multiproc) if sys.platform != 'win32': monkey_patch_os('fork', create_warn_multiproc) try: import _posixsubprocess monkey_patch_module(_posixsubprocess, 'fork_exec', create_warn_fork_exec) except ImportError: pass else: # Windows try: import _subprocess except ImportError: import _winapi as _subprocess monkey_patch_module(_subprocess, 'CreateProcess', create_CreateProcessWarnMultiproc)
def _reload(): global _reload_attempted _reload_attempted = True for fn in _reload_hooks: fn() if hasattr(signal, "setitimer"): # Clear the alarm signal set by # ioloop.set_blocking_log_threshold so it doesn't fire # after the exec. signal.setitimer(signal.ITIMER_REAL, 0, 0) if sys.platform == 'win32': # os.execv is broken on Windows and can't properly parse command line # arguments and executable name if they contain whitespaces. subprocess # fixes that behavior. subprocess.Popen([sys.executable] + sys.argv) sys.exit(0) else: try: os.execv(sys.executable, [sys.executable] + sys.argv) except OSError: # Mac OS X versions prior to 10.6 do not support execv in # a process that contains multiple threads. Instead of # re-executing in the current process, start a new one # and cause the current process to exit. This isn't # ideal since the new process is detached from the parent # terminal and thus cannot easily be killed with ctrl-C, # but it's better than not being able to autoreload at # all. # Unfortunately the errno returned in this case does not # appear to be consistent, so we can't easily check for # this error specifically. os.spawnv(os.P_NOWAIT, sys.executable, [sys.executable] + sys.argv) sys.exit(0)
def main(): with open('.bncbot.pid', 'w') as pid_file: pid_file.write(str(os.getpid())) conn = Conn(bot.HANDLERS) original_sigint = signal.getsignal(signal.SIGINT) def handle_sig(sig, frame): if sig == signal.SIGINT: if conn: asyncio.run_coroutine_threadsafe(conn.shutdown(), conn.loop) signal.signal(signal.SIGINT, original_sigint) elif sig == signal.SIGHUP: if conn: asyncio.run_coroutine_threadsafe(conn.shutdown(True), conn.loop) signal.signal(signal.SIGINT, handle_sig) signal.signal(signal.SIGHUP, handle_sig) restart = conn.run() if restart: conn = None time.sleep(1) os.chdir(original_wd) args = sys.argv for f in [sys.stdout, sys.stderr]: f.flush() os.execv(sys.executable, [sys.executable] + args)
def restart(self): logger.info("Restarting the market maker...") os.execv(sys.executable, [sys.executable] + sys.argv) # # Helpers #
def restart(self): cherrypy.engine.exit() if (os.path.exists(os.path.join(gazee.DATA_DIR, 'db.lock'))): os.remove(os.path.join(gazee.DATA_DIR, 'db.lock')) popen_list = [sys.executable, gazee.FULL_PATH] popen_list += gazee.ARGS print("Gazee is restarting") logging.info('Restarting Gazee with ' + str(popen_list)) if sys.platform == 'win32': subprocess.Popen(popen_list, cwd=os.getcwd()) os._exit(0) else: os.execv(sys.executable, popen_list) logging.info('Gazee is restarting...') return
def update(self): print "[*] Trying to update the client..." try: with open("client.zip", "rb") as f: cli = f.read() hsh = hashlib.md5(cli).hexdigest() except IOError: hsh = "INVALID" path = Rest.get_update(hsh) if path is not None: shutil.rmtree('engine') shutil.rmtree('client') os.remove('client.py') os.remove('requirements.txt') f = zipfile.ZipFile(path, "r") f.extractall('tmp') f.close() root = 'tmp' + os.sep + 'client' + os.sep shutil.move(root + 'client', '.') shutil.move(root + 'engine', '.') shutil.move(root + 'client.py', '.') shutil.move(root + 'requirements.txt', '.') shutil.rmtree('tmp') args = sys.argv[:] print "[*] Update installed successfully, restarting...\n" args.insert(0, sys.executable) if sys.platform == 'win32': args = ['"%s"' % arg for arg in args] os.execv(sys.executable, args) sys.exit(1) else: print "[!] Client is already the latest version."
def refreshWindow(self): self.btnProcessAgain.setVisible(False) self.btnProcessImage.setVisible(True) self.btnProcessImage.setEnabled(True) os.execv(sys.executable, ['python'] + sys.argv)
def main(): # Finds the path to upload.py, assuming it is in the same directory # as this file. my_dir = os.path.dirname(os.path.abspath(__file__)) upload_py_path = os.path.join(my_dir, 'upload.py') # Adds Google Test discussion group to the cc line if it's not there # already. upload_py_argv = [upload_py_path] found_cc_flag = False for arg in sys.argv[1:]: if arg.startswith(CC_FLAG): found_cc_flag = True cc_line = arg[len(CC_FLAG):] cc_list = [addr for addr in cc_line.split(',') if addr] if GTEST_GROUP not in cc_list: cc_list.append(GTEST_GROUP) upload_py_argv.append(CC_FLAG + ','.join(cc_list)) else: upload_py_argv.append(arg) if not found_cc_flag: upload_py_argv.append(CC_FLAG + GTEST_GROUP) # Invokes upload.py with the modified command line flags. os.execv(upload_py_path, upload_py_argv)