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)
python类execv()的实例源码
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 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 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 _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 _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)