def _clean_upgrade(binary_ok, binary_path, path, temp_path):
if binary_ok:
import stat
# save the permissions from the current binary
old_stat = os.stat(binary_path)
# rename the current binary in order to replace it with the latest
os.rename(binary_path, path + "/old")
os.rename(temp_path, binary_path)
# set the same permissions that had the previous binary
os.chmod(binary_path, old_stat.st_mode | stat.S_IEXEC)
# delete the old binary
os.remove(path + "/old")
print("mongoaudit updated, restarting...")
os.execl(binary_path, binary_path, *sys.argv)
else:
os.remove(temp_path)
print("couldn't download the latest binary")
python类execl()的实例源码
def createProject(self, *args):
self.getLang()
dialog = Gtk.FileChooserDialog("Please choose a folder", self, Gtk.FileChooserAction.SELECT_FOLDER, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, "Select", Gtk.ResponseType.OK))
response = dialog.run()
if response == Gtk.ResponseType.OK:
projectPath = dialog.get_filename()
self.projectPath = projectPath
with open(os.path.join(projectPath, '.pyide-project.json'), 'w+') as f:
defaultSettings = {
'path': projectPath,
'name': projectPath.split('/')[len(projectPath.split('/')) - 1],
'language': self.language
}
json.dump(defaultSettings, f, indent=4, sort_keys=True, separators=(',', ':'))
self.createMainFile()
os.execl(sys.executable, *([sys.executable]+sys.argv+[projectPath]))
dialog.destroy()
def restart(self):
""" Safely restart prism """
import os
import sys
import psutil
import logging
try:
p = psutil.Process(os.getpid())
for handler in p.open_files() + p.connections():
os.close(handler.fd)
except Exception as e:
logging.error(e)
python = sys.executable
os.execl(python, python, *sys.argv)
def fork_and_exec():
""" This routine forks and execs a new child process and keeps track of its PID. Before we fork,
set the current restart epoch in an env variable that processes can read if they care. """
global restart_epoch
os.environ['RESTART_EPOCH'] = str(restart_epoch)
print ("forking and execing new child process at epoch {}".format(restart_epoch))
restart_epoch += 1
child_pid = os.fork()
if child_pid == 0:
# Child process
os.execl(sys.argv[1], sys.argv[1])
else:
# Parent process
print ("forked new child process with PID={}".format(child_pid))
pid_list.append(child_pid)
def main():
if len(sys.argv) < 2 or sys.argv[1] == "-h":
print(USAGE)
return
log.debug("sys.argv: %s", sys.argv)
root_dir = _ddtrace_root()
log.debug("ddtrace root: %s", root_dir)
bootstrap_dir = os.path.join(root_dir, 'bootstrap')
log.debug("ddtrace bootstrap: %s", bootstrap_dir)
_add_bootstrap_to_pythonpath(bootstrap_dir)
log.debug("PYTHONPATH: %s", os.environ['PYTHONPATH'])
log.debug("sys.path: %s", sys.path)
executable = sys.argv[1]
# Find the executable path
executable = spawn.find_executable(executable)
log.debug("program executable: %s", executable)
os.execl(executable, executable, *sys.argv[2:])
def restart_program():
"""Restarts the current program.
Note: this function does not return. Any cleanup action (like
saving data) must be done before calling this function."""
python = sys.executable
os.execl(python, python, * sys.argv)
def _clean_upgrade(binary_ok, binary_path, path, temp_path):
if binary_ok:
import stat
# save the permissions from the current binary
old_stat = os.stat(binary_path)
# rename the current binary in order to replace it with the latest
os.rename(binary_path, path + "/old")
os.rename(temp_path, binary_path)
# set the same permissions that had the previous binary
os.chmod(binary_path, old_stat.st_mode | stat.S_IEXEC)
# delete the old binary
os.remove(path + "/old")
print("mongoaudit updated, restarting...")
os.execl(binary_path, binary_path, *sys.argv)
else:
os.remove(temp_path)
print("couldn't download the latest binary")
def dealarm_shell(tube):
"""Given a tube which is a shell, dealarm it.
"""
tube.clean()
tube.sendline('which python')
if tube.recvline().startswith('/'):
tube.sendline('''exec python -c "import signal, os; signal.alarm(0); os.execl('$SHELL','')"''')
return tube
tube.sendline('which perl')
if tube.recvline().startswith('/'):
tube.sendline('''exec perl -e "alarm 0; exec '$SHELL'"''')
return tube
return None
def fork_and_exec():
""" This routine forks and execs a new child process and keeps track of its PID. Before we fork,
set the current restart epoch in an env variable that processes can read if they care. """
global restart_epoch
os.environ['RESTART_EPOCH'] = str(restart_epoch)
print "forking and execing new child process at epoch {}".format(restart_epoch)
restart_epoch += 1
child_pid = os.fork()
if child_pid == 0:
# Child process
os.execl(sys.argv[1], sys.argv[1])
else:
# Parent process
print "forked new child process with PID={}".format(child_pid)
pid_list.append(child_pid)
def update(event_user, event_channel, event, slack_client: Client, **kwargs):
'''
Pulls from git and reloads the process.
'''
if slack_client.admin != event_user:
slack_client.delete_message(event)
g = git.cmd.Git('.')
try:
g.pull()
except:
slack_client.send_message(event_channel, f'Could not git pull.')
return
# This will not return. Instead, the process will be immediately replaced.
os.execl(sys.executable, *([sys.executable] + sys.argv))
def dealarm_shell(tube):
"""Given a tube which is a shell, dealarm it.
"""
tube.clean()
tube.sendline('which python')
if tube.recvline().startswith('/'):
tube.sendline('''exec python -c "import signal, os; signal.alarm(0); os.execl('$SHELL','')"''')
return tube
tube.sendline('which perl')
if tube.recvline().startswith('/'):
tube.sendline('''exec perl -e "alarm 0; exec '$SHELL'"''')
return tube
return None
def cb_button_settings(self, button):
self.main_window.hide()
while Gtk.events_pending():
Gtk.main_iteration()
launch_command = self.install_dir + '/' + self.game_name + '/settings.sh ' + \
self.install_dir + ' ' + nebula_dir
os.system(launch_command)
self.config_save()
os.execl(sys.executable, 'python', __file__, self.game_name)
def cb_button_settings(self, button):
self.main_window.hide()
while Gtk.events_pending():
Gtk.main_iteration()
self.set_wineprefix()
self.create_link()
self.set_environ()
self.set_win_ver_command()
self.set_additions_command()
launch_command = self.install_dir + '/' + self.game_name + '/settings.sh'
full_command = self.win_ver_command + '\n' + \
self.additions_command + '\n' + \
launch_command
os.system(full_command)
self.config_save()
self.exe_path = self.get_new_exe_path()
os.execl(sys.executable, 'python', __file__, self.game_name, self.exe_path)
def notebook_page_switched(self, notebook, widget, arg):
# Automatically check for new games (not a good idea)
#~ if (widget.get_name() == 'goglib_tab') and (self.last_active_tab == 'gogcom_tab'):
#~ if self.goglib_offline_mode:
#~ if goglib_authorized:
#~ os.execl(sys.executable, sys.executable, *sys.argv)
#~ else:
#~ for i in range (self.notebook.get_n_pages()):
#~ try:
#~ if self.notebook.get_nth_page(i) == self.unauthorized_grid:
#~ if goglib_authorized:
#~ os.execl(sys.executable, sys.executable, *sys.argv)
#~ except:
#~ pass
#~ if (self.last_active_tab == 'gogcom_tab') and goglib_authorized:
#~ self.check_for_new_games()
if self.last_active_tab == 'settings_tab':
self.config_save()
if widget.get_name() != 'goglib_tab':
self.button_update_goglib.set_visible(False)
self.button_online_status.set_visible(False)
else:
self.button_online_status.set_visible(True)
if not self.goglib_offline_mode:
self.button_update_goglib.set_visible(True)
self.last_active_tab = widget.get_name()
def cb_button_get_scripts(self, button):
lib = button.get_name()
if lib == 'goglib':
overwrite = self.checkbutton_goglib_scripts.get_active()
elif lib == 'mylib':
overwrite = self.checkbutton_mylib_scripts.get_active()
self.main_window.hide()
if len(self.additional_windows_list) != 0:
for window in self.additional_windows_list:
window.hide()
while Gtk.events_pending():
Gtk.main_iteration()
mylib_has_new_scripts = os.system('python2 ' + nebula_dir + '/get_scripts.py ' + lib + ' ' + str(overwrite))
# Ugly but works
if mylib_has_new_scripts == 0:
print("No new scripts.")
else:
print("New scripts downloaded!")
os.execl(sys.executable, 'python2', __file__)
self.main_window.show()
if len(self.additional_windows_list) != 0:
for window in self.additional_windows_list:
window.show()
def cb_button_online_status(self, button):
if self.goglib_offline_mode:
self.goglib_offline_mode_at_start = False
else:
self.goglib_offline_mode_at_start = True
self.config_save()
os.execl(sys.executable, sys.executable, *sys.argv)
def key_handler(key):
if key in ('q', 'Q', 'esc'):
raise urwid.ExitMainLoop()
elif key == 'ctrl r':
python = sys.executable
os.execl(python, python, *sys.argv)
def openstack_upgrade():
"""Perform action-managed OpenStack upgrade.
Upgrades packages to the configured openstack-origin version and sets
the corresponding action status as a result.
If the charm was installed from source we cannot upgrade it.
For backwards compatibility a config flag (action-managed-upgrade) must
be set for this code to run, otherwise a full service level upgrade will
fire on config-changed."""
if (do_action_openstack_upgrade('keystone',
do_openstack_upgrade,
register_configs())):
os.execl('./hooks/config-changed-postupgrade', '')
def do_openstack_upgrade_reexec(configs):
do_openstack_upgrade(configs)
log("Re-execing hook to pickup upgraded packages", level=INFO)
os.execl('./hooks/config-changed-postupgrade', '')
def do_openstack_upgrade_reexec(configs):
do_openstack_upgrade(configs)
log("Re-execing hook to pickup upgraded packages", level=INFO)
os.execl('./hooks/config-changed-postupgrade', '')
def openProject(self, *args):
dialog = Gtk.FileChooserDialog('Select a project folder', self, Gtk.FileChooserAction.SELECT_FOLDER,(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
response = dialog.run()
if response == Gtk.ResponseType.OK:
projectPath = dialog.get_filename()
os.execl(sys.executable, *([sys.executable]+sys.argv+[projectPath]))
dialog.destroy()
def restart_logic(message, client):
if message.author.id == client.bot_info.owner.id:
await client.send_message(message.channel, 'Restarting... Please wait 5-10 seconds before trying to run any commands!')
os.execl(sys.executable, sys.executable, *sys.argv)
else:
await client.send_message(message.channel, 'ERROR you need to be a bot owner!')
def update_logic(message, client):
if message.author.id in client.bot_info.owner.id:
await client.send_message(message.channel, 'Updating...')
g = git.cmd.Git()
u = g.pull('-v')
await client.send_message(message.channel, '```' + str(u) + '```')
if str(u) == 'Already up-to-date.':
await client.send_message(message.channel, 'Already Up To Date! Not restarting')
else:
await client.send_message(message.channel, 'Update successful restarting!')
os.execl(sys.executable, sys.executable, *sys.argv)
else:
await client.send_message(message.channel, 'Error Didn\'t update maybe you aren\'t an admin?')
def restart(bot, update):
if not from_admin(update):
return
import os
import time
import sys
update.message.reply_text('Restarting {}…'.format(bot.first_name.title()))
time.sleep(0.2)
os.execl(sys.executable, sys.executable, *sys.argv)
def update_bot(message):
if not hasattr(update_bot, "check_sure"):
update_bot.check_sure = True
return
my_bot.reply_to(message, "??, ????? ?? ??????????...")
user_action_log(message, "remotely ran update script.")
os.execl('/bin/bash', 'bash', 'bot_update.sh')
def stop(inp, nick=None, conn=None):
"""stop [reason] -- Kills the bot with [reason] as its quit message."""
if inp:
conn.cmd("QUIT", ["Killed by {} ({})".format(nick, inp)])
else:
conn.cmd("QUIT", ["Killed by {}.".format(nick)])
time.sleep(5)
os.execl("./bot", "bot", "stop")
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 on_private_message(self, msg: discord.Message):
if re.match(r'restart', msg.content):
await self.client.send_message(msg.channel, 'Restarting now...')
await self.client.logout()
os.execl(sys.executable, sys.executable, *sys.argv)
elif re.match(r'shutdown', msg.content):
await self.client.send_message(msg.channel, 'Shutting down...')
await self.client.logout()
sys.exit(0)
def restart_program():
# ????
python = sys.executable
os.execl(python, python, * sys.argv)