Python os.exit() Examples

The following are 30 code examples of os.exit(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: wspbus.py    From moviegrabber with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #2
Source File: ts_extract.py    From arib with Apache License 2.0 6 votes vote down vote up
def main():
  global pid

  parser = argparse.ArgumentParser(description='Draw CC Packets from MPG2 Transport Stream file.')
  parser.add_argument('infile', help='Input filename (MPEG2 Transport Stream File)', type=str)
  parser.add_argument('-p', '--pid', help='Specify a PID of a PES known to contain closed caption info (tool will attempt to find the proper PID if not specified.).', type=int, default=-1)
  args = parser.parse_args()

  infilename = args.infile
  pid = args.pid

  if not os.path.exists(infilename):
    print 'Input filename :' + infilename + " does not exist."
    os.exit(-1)

  ts = TS(infilename)

  ts.Progress = OnProgress
  ts.OnTSPacket = OnTSPacket
  ts.OnESPacket = OnESPacket

  ts.Parse() 
Example #3
Source File: ts.py    From arib with Apache License 2.0 6 votes vote down vote up
def main():

  parser = argparse.ArgumentParser(description='Draw CC Packets from MPG2 Transport Stream file.')
  parser.add_argument('infile', help='Input filename (MPEG2 Transport Stream File)', type=str)
  args = parser.parse_args()

  infilename = args.infile

  if not os.path.exists(infilename):
    print 'Input filename :' + infilename + " does not exist."
    os.exit(-1)

  ts = TS(infilename)

  ts.Progress = OnProgress
  ts.OnTSPacket = OnTSPacket
  ts.OnESPacket = OnESPacket

  ts.Parse() 
Example #4
Source File: wspbus.py    From opsbro with MIT License 6 votes vote down vote up
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 
Example #5
Source File: wspbus.py    From opsbro with MIT License 6 votes vote down vote up
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 
Example #6
Source File: ns-copytons.py    From ns-letsencrypt with GNU General Public License v3.0 6 votes vote down vote up
def getAuthCookie(connectiontype,nitroNSIP,nitroUser,nitroPass):
   url = '%s://%s/nitro/v1/config/login' % (connectiontype, nitroNSIP)
   headers = {'Content-type': 'application/vnd.com.citrix.netscaler.login+json'}
   json_string = {
       "login":{
       "username":nitroUser,
       "password":nitroPass,
       }
   }
   payload = json.dumps(json_string)
   try:
     response = requests.post(url, data=payload, headers=headers, verify=False, timeout=1.0)
     response.raise_for_status()      
   except requests.exceptions.RequestException as e:
     print(e)
     sys.exit(1)
   except requests.exceptions.HTTPError as err:
     print(err)
     sys.exit(1)
    
   cookie = response.cookies['NITRO_AUTH_TOKEN']
   nitroCookie = 'NITRO_AUTH_TOKEN=%s' % cookie
   return nitroCookie 
Example #7
Source File: worker.py    From cellblender with GNU General Public License v2.0 6 votes vote down vote up
def _setup_working_path(self):
        if self.path is None:
            # work in temp folder
            temp_folder = tempfile.mkdtemp()
            os.chdir(temp_folder)
            return temp_folder
        else:
            if not os.path.isider(self.path):
                print("Given simulation path does not exist or invalid, trying to create")
                try:
                    os.mkdir(path)
                except OSError:
                    print("Failed to create given path")
                    os.exit(1)
            os.chdir(self.path)
            return self.path 
Example #8
Source File: wspbus.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #9
Source File: wspbus.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #10
Source File: selector.py    From qpid-python with Apache License 2.0 6 votes vote down vote up
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: 
Example #11
Source File: wspbus.py    From moviegrabber with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #12
Source File: wspbus.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
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 Exception:
            self.log('Shutting down due to error in start listener:',
                     level=40, traceback=True)
            e_info = sys.exc_info()[1]
            try:
                self.exit()
            except Exception:
                # Any stop/exit errors will be logged inside publish().
                pass
            # Re-raise the original error
            raise e_info 
Example #13
Source File: adb.py    From nathan with MIT License 5 votes vote down vote up
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) 
Example #14
Source File: wspbus.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
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 http://www.cherrypy.org/ticket/581.
        # It's also good to let them all shut down before allowing
        # the main thread to call atexit handlers.
        # See http://www.cherrypy.org/ticket/751.
        self.log("Waiting for child threads to terminate...")
        for t in threading.enumerate():
            if t != threading.currentThread() and t.isAlive():
                # 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() 
Example #15
Source File: server_pool.py    From shadowsocksr-python with Apache License 2.0 5 votes vote down vote up
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() 
Example #16
Source File: run_energyplus.py    From rl-testbed-for-energyplus with MIT License 5 votes vote down vote up
def train(env_id, num_timesteps, seed):
    import baselines.common.tf_util as U
    sess = U.single_threaded_session()
    sess.__enter__()
    workerseed = seed + 10000 * MPI.COMM_WORLD.Get_rank()
    def policy_fn(name, ob_space, ac_space):
        return MlpPolicy(name=name, ob_space=ob_space, ac_space=ac_space,
            hid_size=32, num_hid_layers=2)

    # Create a new base directory like /tmp/openai-2018-05-21-12-27-22-552435
    log_dir = os.path.join(energyplus_logbase_dir(), datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"))
    if not os.path.exists(log_dir + '/output'):
        os.makedirs(log_dir + '/output')
    os.environ["ENERGYPLUS_LOG"] = log_dir
    model = os.getenv('ENERGYPLUS_MODEL')
    if model is None:
        print('Environment variable ENERGYPLUS_MODEL is not defined')
        os.exit()
    weather = os.getenv('ENERGYPLUS_WEATHER')
    if weather is None:
        print('Environment variable ENERGYPLUS_WEATHER is not defined')
        os.exit()

    rank = MPI.COMM_WORLD.Get_rank()
    if rank == 0:
        print('train: init logger with dir={}'.format(log_dir)) #XXX
        logger.configure(log_dir)
    else:
        logger.configure(format_strs=[])
        logger.set_level(logger.DISABLED)

    env = make_energyplus_env(env_id, workerseed)

    trpo_mpi.learn(env, policy_fn,
                   max_timesteps=num_timesteps,
                   #timesteps_per_batch=1*1024, max_kl=0.01, cg_iters=10, cg_damping=0.1,
                   timesteps_per_batch=16*1024, max_kl=0.01, cg_iters=10, cg_damping=0.1,
                   gamma=0.99, lam=0.98, vf_iters=5, vf_stepsize=1e-3)
    env.close() 
Example #17
Source File: wspbus.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
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() 
Example #18
Source File: wspbus.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
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 = []
        
        items = [(self._priorities[(channel, listener)], listener)
                 for listener in self.listeners[channel]]
        try:
            items.sort(key=lambda item: item[0])
        except TypeError:
            # Python 2.3 had no 'key' arg, but that doesn't matter
            # since it could sort dissimilar types just fine.
            items.sort()
        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 
Example #19
Source File: plot_energyplus.py    From rl-testbed-for-energyplus with MIT License 5 votes vote down vote up
def energyplus_plot(env_id, log_dir='', csv_file='', dump_timesteps=False, dump_episodes=False):
    if log_dir is not '' and csv_file is not '':
        print('Either log directory or csv file can be specified')
        os.exit(1)
    if log_dir is '' and csv_file is '':
        log_dir = energyplus_locate_log_dir()
    env = make_energyplus_env(env_id, 0)
    assert sum([dump_timesteps, dump_episodes]) != 2
    if dump_timesteps:
        env.env.dump_timesteps(log_dir=log_dir, csv_file=csv_file)
    elif dump_episodes:
        env.env.dump_episodes(log_dir=log_dir, csv_file=csv_file)
    else:
        env.env.plot(log_dir=log_dir, csv_file=csv_file)
    env.close() 
Example #20
Source File: nathan.py    From nathan with MIT License 5 votes vote down vote up
def error_msg(msg):
    print msg
    os.exit(1) 
Example #21
Source File: wspbus.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        """Initialize pub/sub bus."""
        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 = {} 
Example #22
Source File: wspbus.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.execv = False
        self.state = states.STOPPED
        self.listeners = dict(
            [(channel, set()) for channel
             in ('start', 'stop', 'exit', 'graceful', 'log', 'main')])
        self._priorities = {} 
Example #23
Source File: wspbus.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def exit(self):
        """Stop all services and prepare to exit the process."""
        exitstate = self.state
        EX_SOFTWARE = 70
        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 Exception:
            # 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(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(EX_SOFTWARE) 
Example #24
Source File: wspbus.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
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 = {} 
Example #25
Source File: wspbus.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #26
Source File: wspbus.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
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() 
Example #27
Source File: wspbus.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def _clean_exit(self):
        """Assert that the Bus is not running in atexit handler callback."""
        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() 
Example #28
Source File: wspbus.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
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 Exception:
                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 
Example #29
Source File: BDWK.py    From bdwenku-spider with GNU General Public License v3.0 5 votes vote down vote up
def main():
	try:
		url = input("请输入资源所在的网址:")
		docType = BaiduWK(url).docType
	except:
		print("您输入的url,有误请重新输入!")
		os.exit()
	print("类型为","-->",docType)

	if docType == "ppt":

		ppt = BDWKPPT(url)
		print("您将要获取的演示文稿(ppt)名称为:", ppt.title)
		ppt.get_ppt_json_info()

	elif docType == "doc":
		word = BDWKDOC(url)
		print("您将要获取的文档(word)名称为", word.title)
		pure_addr_list = word.get_pure_addr_list()
		word.get_json_content(pure_addr_list)

	elif docType == "pdf":
		pdf = BDWKDOC(url)
		print("您将要获取的PDF名称为:", pdf.title)
		pure_addr_list = pdf.get_pure_addr_list()
		pdf.get_json_content(pure_addr_list)

	elif docType == "txt":

		txt = BDWKTXT(url)
		print("您将要下载的文本文档(txt)名称为:", txt.title)
		txt.get_txt(url)

	else:
		other = BDWKPPT(url)
		print("暂不支持下载%s类型"%(other.docType))
		pass 
Example #30
Source File: wspbus.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def exit(self):
        """Stop all services and prepare to exit the process."""
        exitstate = self.state
        EX_SOFTWARE = 70
        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 Exception:
            # 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(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(EX_SOFTWARE)