def ContactGroupL394(**kwargs): with _TDir(suffix="_mdciao_example_CG") as t: for fn in [ filenames.pdb_3SN6, filenames.traj_xtc, filenames.top_pdb, filenames.adrb2_human_xlsx, filenames.CGN_3SN6 ]: _link(fn, _path.join(t, _path.basename(fn))) with remember_cwd(): _chdir(t) b = _io.StringIO() try: with _contextlib.redirect_stdout(b): example_kwargs = { "topology": _path.basename(filenames.top_pdb), "n_smooth_hw": 1, "figures": False, "BW_uniprot": _path.basename(filenames.adrb2_human_xlsx), "CGN_PDB": _path.basename(filenames.CGN_3SN6), "accept_guess": True } for key, val in kwargs.items(): example_kwargs[key] = val return _residue_neighborhoods( "L394", _path.basename(filenames.traj_xtc), **example_kwargs, )["neighborhoods"][353] except Exception as e: print(b.getvalue()) b.close() raise e
def startup(): '''Do basic setup for the program. This really should only be run once but has some basic tests to prevent double-assignment''' _chdir(sys.path[0]) _makedirs("logs", exist_ok=True) global args, logger, loop args = parseargs() loop = asyncio.get_event_loop() # Set up logging open(settings.logfile, 'w').close() logger = logging.getLogger(__name__) rootLogger = logging.getLogger() if len(rootLogger.handlers) is 0: rootLogger.setLevel(logging.DEBUG) conFmt = "[%(levelname)8s] %(name)s: %(message)s" ch = logging.StreamHandler() ch.setFormatter(logging.Formatter(conFmt)) rootLogger.addHandler(ch) filFmt = "[%(levelname)8s] %(asctime)s %(name)s: %(message)s" fh = logging.FileHandler(settings.logfile) fh.setFormatter(logging.Formatter(filFmt, "%b-%d %H:%M:%S")) rootLogger.addHandler(fh) util.setLogLevel(args.verbose, True) logger.debug('Logging set up.') logger.debug('Args state: {}'.format(args)) logger.info('Badge check midlayer v{} starting on {} ({})'.format( settings.version, datetime.now().date(), datetime.now().date().strftime("%A"))) # Set up API key try: with open(getSetting('apikey')) as f: settings.magapi.headers['X-Auth-Token'] = str( UUID(f.read().strip())) except FileNotFoundError: logger.fatal( 'Could not find API key file, refusing to run. ({})'.format( path.abspath(getSetting('apikey')))) raise SystemExit except ValueError: logger.fatal('API key not a valid UUID, refusing to run.') raise SystemExit global server try: server except NameError: server = loop.run_until_complete( websockets.serve( prcsConnection, socket.gethostbyname_ex(socket.getfqdn())[-1] + ['127.0.0.1'], getSetting('l_port'))) for s in server.sockets: logger.info('Now listening for connections on {}:{}'.format( *s.getsockname()))
import os from os import chdir as _chdir from unittest import TestCase from mock import patch import tut.sphinx from tut.tests import util from tut.tests.util import with_sphinx @patch('os.chdir', new=lambda x: _chdir(x) if os.path.exists(x) else None) @patch('tut.sphinx.git', return_value='original_branch') class SphinxExtensionLifecycleTests(TestCase): # the order of these decorators is *important*: cleanup needs to # be replaced before the Sphinx Test Application is instantiated @patch('tut.sphinx.cleanup') @with_sphinx() def test_cleanup_called(self, cleanup_mock, git_mock, sphinx_app=None): sphinx_app.build(force_all=True) self.assertEqual(cleanup_mock.call_count, 1) @with_sphinx() def test_cleanup_resets_paths(self, git_mock, sphinx_app=None): start_dir = os.getcwd() sphinx_app.build()
def exec(self, args: tuple = (), **kwargs): """Execute the command. """ app_path = _reg.get('paths.app') config_path = _reg.get('paths.config') stage = self.opt('stage') stop_after = self.opt('stop-after') _chdir(app_path) _maintenance.enable() d = self._get_update_data() if not d['update_in_progress']: d['pytsite_version_from'] = str(_package_info.version('pytsite')) d['app_version_from'] = str(_package_info.version('app')) d['update_in_progress'] = True self._set_update_data(d) # Stage 1: update pip and PytSite if stage == 1: _console.print_info(_lang.t('pytsite.update@updating_environment')) # Update pip _pip.install('pip', None, True, self.opt('debug')) # Update PytSite _pip.install('pytsite', _package_info.requires_pytsite('app'), True, self.opt('debug')) d['pytsite_version_to'] = str(_package_info.version('pytsite', False)) self._set_update_data(d) # Notify listeners _events.fire('pytsite.update@stage_1') if stop_after != 1: _subprocess.call(['./console', 'update', '--stage=2']) else: _maintenance.disable() # Stage 2: update application and configuration elif stage == 2: # Notify listeners about PytSite update _events.fire('pytsite.update@pytsite', v_from=_semver.Version(d['pytsite_version_from'])) # Update configuration if _path.exists(_path.join(config_path, '.git')): _console.print_info(_lang.t('pytsite.update@updating_configuration')) _subprocess_run(['git', '-C', config_path, 'pull']) # Update application if _path.exists(_path.join(app_path, '.git')): _console.print_info(_lang.t('pytsite.update@updating_application')) _subprocess_run(['git', '-C', app_path, 'pull']) d['app_version_to'] = str(_package_info.version('app', False)) self._set_update_data(d) # Notify listeners _events.fire('pytsite.update@stage_2') if stop_after != 2: _subprocess.call(['./console', 'update', '--stage=3']) else: _maintenance.disable() # Stage 3: finish update process elif stage == 3: _console.print_info(_lang.t('pytsite.update@applying_updates')) # Notify listeners about application update _events.fire('pytsite.update@app', v_from=_semver.Version(d['app_version_from'])) # Notify listeners _events.fire('pytsite.update@update') # Application's update hook import app if hasattr(app, 'app_update') and callable(app.app_update): app.app_update(v_from=_semver.Version(d['app_version_from'])) # Mark that update was finished successfully d['update_in_progress'] = False self._set_update_data(d) # Disable maintenance mode _maintenance.disable() # Reload the application _reload.reload()
def os_chdir(path): return os._chdir(longpathify(uni(path)))
def remember_cwd(): curdir = _getcwd() try: yield finally: _chdir(curdir)