我们从Python开源项目中,提取了以下36个代码示例,用于说明如何使用os.exit()。
def Set( self ): if self.package_installed( 'wget' ): print( '\r\n\r\n[WGET]' ) if self.verbose: print '%s Wget is installed, opening %s for writing ' % ( self.date(), self.wgetrc ) try: self.backup_config( self.wgetrc ) config = ConfigObj( self.wgetrc ) config[ 'http_proxy' ] = self.http config[ 'https_proxy' ] = self.http config[ 'ftp_proxy' ] = self.http config[ 'use_proxy' ] = 'on' config.write( open( self.wgetrc, 'w' ) ) if self.verbose: print( '%s Proxy configuration written successfully to %s ' % ( self.date(), self.wgetrc ) ) except ( IOError, ConfigObjError ), e: print( 'Unable to set wget proxy: Error reading wget config in \'%s\' - %s' % ( self.wgetrc, e ) ) os.exit( 1 ) else: print( '%s Wget not installed, skipping' % self.date() ) super( Wget, self ).Set()
def Unset( self ): if self.package_installed( 'wget' ): print( '\r\n\r\n[WGET]' ) if self.verbose: print( '%s Wget is installed, opening %s for writing ' % ( self.date(), self.wgetrc ) ) try: config = ConfigObj( self.wgetrc ) if config.has_key( 'http_proxy' ): del config[ 'http_proxy' ] if config.has_key( 'https_proxy' ): del config[ 'https_proxy' ] if config.has_key( 'ftp_proxy' ): del config[ 'ftp_proxy' ] config[ 'use_proxy' ] = 'off' config.write( open( self.wgetrc, 'w' ) ) if self.verbose: print( '%s Proxy configuration removed successfully from %s ' % ( self.date(), self.wgetrc ) ) except ( IOError, ConfigObjError ), e: print( 'Unable to unset wget proxy: Error reading wget config in \'%s\' - %s' % ( self.wgetrc, e ) ) os.exit( 1 ) else: print( '%s Wget not installed, skipping' % self.date() ) super( Wget, self ).Unset()
def TeeCmd(cmd, logfile, fail_hard=True): """Runs cmd and writes the output to both stdout and logfile.""" # Reading from PIPE can deadlock if one buffer is full but we wait on a # different one. To work around this, pipe the subprocess's stderr to # its stdout buffer and don't give it a stdin. # shell=True is required in cmd.exe since depot_tools has an svn.bat, and # bat files only work with shell=True set. proc = subprocess.Popen(cmd, bufsize=1, shell=sys.platform == 'win32', stdin=open(os.devnull), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in iter(proc.stdout.readline,''): Tee(line, logfile) if proc.poll() is not None: break exit_code = proc.wait() if exit_code != 0 and fail_hard: print 'Failed:', cmd sys.exit(1)
def MaybeUpload(args, archive_name, platform): # We don't want to rewrite the file, if it already exists on the server, # so -n option to gsutil is used. It will warn, if the upload was aborted. gsutil_args = ['cp', '-n', '-a', 'public-read', '%s.tgz' % archive_name, 'gs://chromium-browser-clang/%s/%s.tgz' % (platform, archive_name)] if args.upload: print 'Uploading %s to Google Cloud Storage...' % archive_name exit_code = RunGsutil(gsutil_args) if exit_code != 0: print "gsutil failed, exit_code: %s" % exit_code os.exit(exit_code) else: print 'To upload, run:' print ('gsutil %s' % ' '.join(gsutil_args))
def lookup_appdata_folder(): from os import path, environ if sys.platform == 'darwin': if "HOME" in environ: data_folder = path.join(os.environ["HOME"], "Library/Application support/", global_singleton.APPNAME) + '/' else: print("Could not find home folder") os.exit() elif 'win32' in sys.platform or 'win64' in sys.platform: data_folder = path.join(environ['APPDATA'], global_singleton.APPNAME) + '\\' else: data_folder = path.expanduser(path.join("~", "." + global_singleton.APPNAME + "/")) return data_folder
def test_use_after_fork(self): c = Connection.establish(self.broker) pid = os.fork() if pid: # Parent self.assertEqual((pid, 0), os.waitpid(pid, 0)) self.assertEqual("child", c.session().receiver("child;{create:always}").fetch().content) else: # Child try: # Can establish new connections s = Connection.establish(self.broker).session().sender("child;{create:always}") self.assertRaises(SelectorStopped, c.session) # But can't use parent connection s.send("child") os._exit(0) except Exception, e: print >>sys.stderr, "test child process error: %s" % e os.exit(1) finally: os._exit(1) # Hard exit from child to stop remaining tests running twice
def start(self): """Start all services.""" atexit.register(self._clean_exit) self.state = states.STARTING self.log('Bus STARTING') try: self.publish('start') self.state = states.STARTED self.log('Bus STARTED') except (KeyboardInterrupt, SystemExit): raise except: self.log('Shutting down due to error in start listener:', level=40, traceback=True) e_info = sys.exc_info()[1] try: self.exit() except: # Any stop/exit errors will be logged inside publish(). pass # Re-raise the original error raise e_info
def exit(self): """Stop all services and prepare to exit the process.""" exitstate = self.state try: self.stop() self.state = states.EXITING self.log('Bus EXITING') self.publish('exit') # This isn't strictly necessary, but it's better than seeing # "Waiting for child threads to terminate..." and then nothing. self.log('Bus EXITED') except: # This method is often called asynchronously (whether thread, # signal handler, console handler, or atexit handler), so we # can't just let exceptions propagate out unhandled. # Assume it's been logged and just die. os._exit(70) # EX_SOFTWARE if exitstate == states.STARTING: # exit() was called before start() finished, possibly due to # Ctrl-C because a start listener got stuck. In this case, # we could get stuck in a loop where Ctrl-C never exits the # process, so we just call os.exit here. os._exit(70) # EX_SOFTWARE
def start(self): """Start all services.""" atexit.register(self._clean_exit) self.state = states.STARTING self.log('Bus STARTING') try: self.publish('start') self.state = states.STARTED self.log('Bus STARTED') except (KeyboardInterrupt, SystemExit): raise except: self.log("Shutting down due to error in start listener:", level=40, traceback=True) e_info = sys.exc_info()[1] try: self.exit() except: # Any stop/exit errors will be logged inside publish(). pass # Re-raise the original error raise e_info
def _loop(loop, dns_resolver, mgr): try: if mgr is not None: mgr.add_to_loop(loop) dns_resolver.add_to_loop(loop) loop.run() except (KeyboardInterrupt, IOError, OSError) as e: logging.error(e) traceback.print_exc() os.exit(0) except Exception as e: logging.error(e) traceback.print_exc()
def GetGsutilPath(): if not 'find_depot_tools' in sys.modules: sys.path.insert(0, os.path.join(CHROMIUM_DIR, 'build')) global find_depot_tools import find_depot_tools depot_path = find_depot_tools.add_depot_tools_to_path() if depot_path is None: print ('depot_tools are not found in PATH. ' 'Follow the instructions in this document ' 'http://dev.chromium.org/developers/how-tos/install-depot-tools' ' to install depot_tools and then try again.') sys.exit(1) gsutil_path = os.path.join(depot_path, 'gsutil.py') return gsutil_path
def generate_context_feature(in_data_dir1, in_data_dir2, out_data_dir, dimension1, dimension2): if not os.path.exists(out_data_dir): os.makedirs(out_data_dir) file_paths, filenames = read_file_list(in_data_dir1) context_features = numpy i = 0 for file_path, filename in zip(file_paths, filenames): features1, frame_number1 = load_binary_file(file_path, dimension1) features2, frame_number2 = load_binary_file(os.path.join(in_data_dir2, filename), dimension2) if frame_number1 != frame_number2: print(dimension2) print(filename) print("%s %d != %d" %(filename, frame_number1, frame_number2)) print(features1.shape, features2.shape) os.exit(1) context_features = numpy.zeros((frame_number1, dimension1+dimension2)) context_features[0:frame_number1, 0:dimension1] = features1 context_features[0:frame_number2, dimension1:dimension1+dimension2] = features2 print(filename, features1.shape, features2.shape, context_features.shape) context_filename = out_data_dir + '/' + filename context_features = numpy.asarray(context_features, 'float32') fid = open(context_filename, 'wb') context_features.tofile(fid) fid.close()
def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) _exit_status = of.broker.broker.stop_broker("Shutting down the Broker service") self.ReportServiceStatus(win32service.SERVICE_STOPPED) os.exit(_exit_status)
def generate_context_feature(in_data_dir1, in_data_dir2, out_data_dir, dimension1, dimension2): if not os.path.exists(out_data_dir): os.makedirs(out_data_dir) file_paths, filenames = read_file_list(in_data_dir1) context_features = numpy i = 0 for file_path, filename in zip(file_paths, filenames): features1, frame_number1 = load_binary_file(file_path, dimension1) features2, frame_number2 = load_binary_file(os.path.join(in_data_dir2, filename), dimension2) if frame_number1 != frame_number2: print dimension2 print filename print "%s %d != %d" %(filename, frame_number1, frame_number2) print features1.shape, features2.shape os.exit(1) context_features = numpy.zeros((frame_number1, dimension1+dimension2)) context_features[0:frame_number1, 0:dimension1] = features1 context_features[0:frame_number2, dimension1:dimension1+dimension2] = features2 print filename, features1.shape, features2.shape, context_features.shape context_filename = out_data_dir + '/' + filename context_features = numpy.asarray(context_features, 'float32') fid = open(context_filename, 'wb') context_features.tofile(fid) fid.close()
def __init__(self): self.execv = False self.state = states.STOPPED channels = 'start', 'stop', 'exit', 'graceful', 'log', 'main' self.listeners = dict( (channel, set()) for channel in channels ) self._priorities = {}
def publish(self, channel, *args, **kwargs): """Return output of all subscribers for the given channel.""" if channel not in self.listeners: return [] exc = ChannelFailures() output = [] raw_items = ( (self._priorities[(channel, listener)], listener) for listener in self.listeners[channel] ) items = sorted(raw_items, key=operator.itemgetter(0)) for priority, listener in items: try: output.append(listener(*args, **kwargs)) except KeyboardInterrupt: raise except SystemExit: e = sys.exc_info()[1] # If we have previous errors ensure the exit code is non-zero if exc and e.code == 0: e.code = 1 raise except: exc.handle_exception() if channel == 'log': # Assume any further messages to 'log' will fail. pass else: self.log('Error in %r listener %r' % (channel, listener), level=40, traceback=True) if exc: raise exc return output
def _clean_exit(self): """An atexit handler which asserts the Bus is not running.""" if self.state != states.EXITING: warnings.warn( 'The main thread is exiting, but the Bus is in the %r state; ' 'shutting it down automatically now. You must either call ' 'bus.block() after start(), or call bus.exit() before the ' 'main thread exits.' % self.state, RuntimeWarning) self.exit()
def batch_make_numbered_dirs(rootdir, repeats): try: for i in range(repeats): dir_ = py.path.local.make_numbered_dir(prefix='repro-', rootdir=rootdir) file_ = dir_.join('foo') file_.write('%s' % i) actual = int(file_.read()) assert actual == i, 'int(file_.read()) is %s instead of %s' % (actual, i) dir_.join('.lock').remove(ignore_errors=True) return True except KeyboardInterrupt: # makes sure that interrupting test session won't hang it os.exit(2)
def send_email(type, message_to_send): msg = MIMEMultipart() msg['From'] = sender msg['To'] = to msg['Subject'] = 'Humble bot instagram - '+ str(type) msg.attach(MIMEText('Hello Anis, this is me, your bot ! I have to say you that : ' + str(message_to_send), 'plain')) mailserver = smtplib.SMTP('smtp.gmail.com', 587) mailserver.ehlo() mailserver.starttls() mailserver.ehlo() mailserver.login(sender, sender_pwd) mailserver.sendmail(sender, to, msg.as_string()) print 'message to '+str(to)+ ' sent !' mailserver.quit() os.exit(1)
def publish(self, channel, *args, **kwargs): """Return output of all subscribers for the given channel.""" if channel not in self.listeners: return [] exc = ChannelFailures() output = [] raw_items = ( (self._priorities[(channel, listener)], listener) for listener in self.listeners[channel] ) items = sorted(raw_items, key=operator.itemgetter(0)) for priority, listener in items: try: output.append(listener(*args, **kwargs)) except KeyboardInterrupt: raise except SystemExit: e = sys.exc_info()[1] # If we have previous errors ensure the exit code is non-zero if exc and e.code == 0: e.code = 1 raise except: exc.handle_exception() if channel == 'log': # Assume any further messages to 'log' will fail. pass else: self.log("Error in %r listener %r" % (channel, listener), level=40, traceback=True) if exc: raise exc return output
def _clean_exit(self): """An atexit handler which asserts the Bus is not running.""" if self.state != states.EXITING: warnings.warn( "The main thread is exiting, but the Bus is in the %r state; " "shutting it down automatically now. You must either call " "bus.block() after start(), or call bus.exit() before the " "main thread exits." % self.state, RuntimeWarning) self.exit()
def run(name, connector, inventory): """Run the bot. By default will run with the first available connector. """ connectors = get_connectors() if len(connectors) == 0: print("ERROR: No available connectors!") os.exit(1) conn_pkg = connectors[0].load() for c in connectors: if c.name == connector: conn_pkg = c.load() inventories = get_inventories() if len(inventories) == 0: print("ERROR: No available inventories!") os.exit(1) for i in inventories: if i.name == inventory: inventory_pkg = i.load() commands = get_commands() print('comm', commands) inventory = inventory_pkg.Inventory() bot = Bot(name, inventory, commands) connector = conn_pkg.Connector(bot) print("Listening for messages...") connector.listen()
def _loop(loop, dns_resolver, mgr): try: if mgr is not None: mgr.add_to_loop(loop) dns_resolver.add_to_loop(loop) loop.run() except (KeyboardInterrupt, IOError, OSError) as e: logging.error(e) import traceback traceback.print_exc() os.exit(0) except Exception as e: logging.error(e) import traceback traceback.print_exc()
def error_msg(msg): print msg os.exit(1)
def run_adb_command(adb_type, command): if adb_type == "local": adb_cmd = EMULATOR_LOCAL_PTOOLS_DIR+ADB_CMD elif adb_type == "path": adb_cmd = ADB_CMD else: print_error("ADB type error!") os.exit(1) return run_command(adb_cmd + " " + command)
def block(self, interval=0.1): """Wait for the EXITING state, KeyboardInterrupt or SystemExit. This function is intended to be called only by the main thread. After waiting for the EXITING state, it also waits for all threads to terminate, and then calls os.execv if self.execv is True. This design allows another thread to call bus.restart, yet have the main thread perform the actual execv call (required on some platforms). """ try: self.wait(states.EXITING, interval=interval, channel='main') except (KeyboardInterrupt, IOError): # The time.sleep call might raise # "IOError: [Errno 4] Interrupted function call" on KBInt. self.log('Keyboard Interrupt: shutting down bus') self.exit() except SystemExit: self.log('SystemExit raised: shutting down bus') self.exit() raise # Waiting for ALL child threads to finish is necessary on OS X. # See https://github.com/cherrypy/cherrypy/issues/581. # It's also good to let them all shut down before allowing # the main thread to call atexit handlers. # See https://github.com/cherrypy/cherrypy/issues/751. self.log('Waiting for child threads to terminate...') for t in threading.enumerate(): # Validate the we're not trying to join the MainThread # that will cause a deadlock and the case exist when # implemented as a windows service and in any other case # that another thread executes cherrypy.engine.exit() if ( t != threading.currentThread() and t.isAlive() and not isinstance(t, threading._MainThread) ): # Note that any dummy (external) threads are always daemonic. if hasattr(threading.Thread, 'daemon'): # Python 2.6+ d = t.daemon else: d = t.isDaemon() if not d: self.log('Waiting for thread %s.' % t.getName()) t.join() if self.execv: self._do_execv()
def block(self, interval=0.1): """Wait for the EXITING state, KeyboardInterrupt or SystemExit. This function is intended to be called only by the main thread. After waiting for the EXITING state, it also waits for all threads to terminate, and then calls os.execv if self.execv is True. This design allows another thread to call bus.restart, yet have the main thread perform the actual execv call (required on some platforms). """ try: self.wait(states.EXITING, interval=interval, channel='main') except (KeyboardInterrupt, IOError): # The time.sleep call might raise # "IOError: [Errno 4] Interrupted function call" on KBInt. self.log('Keyboard Interrupt: shutting down bus') self.exit() except SystemExit: self.log('SystemExit raised: shutting down bus') self.exit() raise # Waiting for ALL child threads to finish is necessary on OS X. # See https://github.com/cherrypy/cherrypy/issues/581. # It's also good to let them all shut down before allowing # the main thread to call atexit handlers. # See https://github.com/cherrypy/cherrypy/issues/751. self.log("Waiting for child threads to terminate...") for t in threading.enumerate(): # Validate the we're not trying to join the MainThread # that will cause a deadlock and the case exist when # implemented as a windows service and in any other case # that another thread executes cherrypy.engine.exit() if ( t != threading.currentThread() and t.isAlive() and not isinstance(t, threading._MainThread) ): # Note that any dummy (external) threads are always daemonic. if hasattr(threading.Thread, "daemon"): # Python 2.6+ d = t.daemon else: d = t.isDaemon() if not d: self.log("Waiting for thread %s." % t.getName()) t.join() if self.execv: self._do_execv()