Python tempfile.tempdir() Examples

The following are code examples for showing how to use tempfile.tempdir(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: dj-wkhtmltopdf   Author: dhanababum   File: utils.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, **kwargs):
        """
        By default it will search django core settings,
        if wkhtmltopdf not found there it will add that command.
        :param kwargs:
        It may contains the html and context,
        html object is model and context of view
        :type kwargs: Dictionary
        :returns: None
        """
        tempfile.tempdir = '/tmp/'
        self.tmp_dir = tempfile.gettempdir()
        self.html = kwargs.get('html')
        self.context = kwargs.get('context')
        self.command = []
        self.code_format = "utf-8"
        if hasattr(settings, "WKHTML_TO_PDF_CMD") and isinstance(settings.WKHTML_TO_PDF_CMD, str):
            self.command = [settings.WKHTML_TO_PDF_CMD] 
Example 2
Project: me-ica   Author: ME-ICA   File: test_image_repositoy.py    GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_module_scope_is_updated_on_patch(expected_attrs):
  '''
  Patch should update the module's globals() on success
  '''
  from gooey.gui import image_repository
  testing_icons = ('config_icon.png', 'success_icon.png')
  try:
    # setup
    make_user_files(*testing_icons)
    old_icon = image_repository.config_icon
    # load up our new icon(s)
    image_repository.patch_images(tempfile.tempdir)
    new_icon = image_repository.config_icon
    assert old_icon != new_icon
  finally:
    cleanup_temp(*testing_icons)


# helpers 
Example 3
Project: pyontutils   Author: tgbugs   File: necromancy.py    MIT License 6 votes vote down vote up
def main():
    from joblib import Parallel, delayed
    args = docopt(__doc__, version = "necromancy 0.5")
    files = args['<file-or-url>']
    url_dest = [(f, '{tempfile.tempdir}/' + os.path.basename(f)) if f.startswith('http://') or f.startswith('https://') else (f, f) for f in files]
    toget = [(u, t) for u, t in url_dest if u != t]
    if toget:
        import requests
        for url, filename in toget:
            resp = requests.get(url, stream=True)
            with open(filename, 'wb') as f:
                for chunk in resp.iter_content(chunk_size=1024):
                    if chunk:
                        f.write(chunk)
        files = list(zip(*url_dest))[1]

    if args['--slow'] or len(files) == 1:
        [load(f) for f in files]
    else:
        Parallel(n_jobs=9)(delayed(load)(f) for f in files) 
Example 4
Project: pyontutils   Author: tgbugs   File: core.py    MIT License 6 votes vote down vote up
def __init__(self, name, prefixes=None, graph=None, writeloc=tempfile.tempdir):
        self.name = name
        self.writeloc = writeloc
        self.namespaces = {}
        if prefixes:
            self.namespaces.update({p:getNamespace(p, ns) for p, ns in prefixes.items()})
        if graph:  # graph takes precidence
            self.namespaces.update({p:getNamespace(p, ns) for p, ns in graph.namespaces()})
        if graph is None and not prefixes:
            raise ValueError('No prefixes or graph specified.')

        if graph is not None:
            self.g = graph
        else:
            self.g = OntGraph()  # default args issue

        for p, ns in self.namespaces.items():
            self.add_namespace(p, ns)
        self.namespaces.update({p:getNamespace(p, ns)
                                for p, ns in self.g.namespaces()})  # catchall for namespaces in self.g 
Example 5
Project: edx-video-worker   Author: edx   File: test_utils.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def setUp(self):
        """
        Tests setup.
        """
        self._orig_environ = dict(os.environ)

        # create a temporary default config file
        _, self.file_path = tempfile.mkstemp(
            suffix='.yml',
            dir=tempfile.tempdir
        )
        with open(self.file_path, 'w') as outfile:
            yaml.dump(TEST_CONFIG, outfile, default_flow_style=False)

        os.environ['VEDA_ENCODE_WORKER_CFG'] = self.file_path

        # create a temporary static config file
        _, self.static_file_path = tempfile.mkstemp(
            suffix='.yml',
            dir=tempfile.tempdir
        )
        with open(self.static_file_path, 'w') as outfile:
            yaml.dump(TEST_STATIC_CONFIG, outfile, default_flow_style=False) 
Example 6
Project: ironpython2   Author: IronLanguages   File: test_tempfile.py    Apache License 2.0 6 votes vote down vote up
def test_exports(self):
        # There are no surprising symbols in the tempfile module
        dict = tempfile.__dict__

        expected = {
            "NamedTemporaryFile" : 1,
            "TemporaryFile" : 1,
            "mkstemp" : 1,
            "mkdtemp" : 1,
            "mktemp" : 1,
            "TMP_MAX" : 1,
            "gettempprefix" : 1,
            "gettempdir" : 1,
            "tempdir" : 1,
            "template" : 1,
            "SpooledTemporaryFile" : 1
        }

        unexp = []
        for key in dict:
            if key[0] != '_' and key not in expected:
                unexp.append(key)
        self.assertTrue(len(unexp) == 0,
                        "unexpected keys: %s" % unexp) 
Example 7
Project: cuny-bdif   Author: aristotle-tek   File: test_uri.py    MIT License 6 votes vote down vote up
def test_explicit_file_uri(self):
        tmp_dir = tempfile.tempdir or ''
        uri_str = 'file://%s' % urllib.request.pathname2url(tmp_dir)
        uri = boto.storage_uri(uri_str, validate=False,
            suppress_consec_slashes=False)
        self.assertEqual('file', uri.scheme)
        self.assertEqual(uri_str, uri.uri)
        self.assertFalse(hasattr(uri, 'versionless_uri'))
        self.assertEqual('', uri.bucket_name)
        self.assertEqual(tmp_dir, uri.object_name)
        self.assertFalse(hasattr(uri, 'version_id'))
        self.assertFalse(hasattr(uri, 'generation'))
        self.assertFalse(hasattr(uri, 'is_version_specific'))
        self.assertEqual(uri.names_provider(), False)
        self.assertEqual(uri.names_bucket(), False)
        # Don't check uri.names_container(), uri.names_directory(),
        # uri.names_file(), or uri.names_object(), because for file URIs these
        # functions look at the file system and apparently unit tests run
        # chroot'd.
        self.assertEqual(uri.is_stream(), False) 
Example 8
Project: cuny-bdif   Author: aristotle-tek   File: test_uri.py    MIT License 6 votes vote down vote up
def test_implicit_file_uri(self):
        tmp_dir = tempfile.tempdir or ''
        uri_str = '%s' % urllib.request.pathname2url(tmp_dir)
        uri = boto.storage_uri(uri_str, validate=False,
            suppress_consec_slashes=False)
        self.assertEqual('file', uri.scheme)
        self.assertEqual('file://%s' % tmp_dir, uri.uri)
        self.assertFalse(hasattr(uri, 'versionless_uri'))
        self.assertEqual('', uri.bucket_name)
        self.assertEqual(tmp_dir, uri.object_name)
        self.assertFalse(hasattr(uri, 'version_id'))
        self.assertFalse(hasattr(uri, 'generation'))
        self.assertFalse(hasattr(uri, 'is_version_specific'))
        self.assertEqual(uri.names_provider(), False)
        self.assertEqual(uri.names_bucket(), False)
        # Don't check uri.names_container(), uri.names_directory(),
        # uri.names_file(), or uri.names_object(), because for file URIs these
        # functions look at the file system and apparently unit tests run
        # chroot'd.
        self.assertEqual(uri.is_stream(), False) 
Example 9
Project: Splunk_CBER_App   Author: MHaggis   File: search_command.py    MIT License 5 votes vote down vote up
def _prepare_protocol_v1(self, argv, ifile, ofile):

        debug = environment.splunklib_logger.debug

        # Provide as much context as possible in advance of parsing the command line and preparing for execution

        self._input_header.read(ifile)
        self._protocol_version = 1
        self._map_metadata(argv)

        debug('  metadata=%r, input_header=%r', self._metadata, self._input_header)

        try:
            tempfile.tempdir = self._metadata.searchinfo.dispatch_dir
        except AttributeError:
            raise RuntimeError('{}.metadata.searchinfo.dispatch_dir is undefined'.format(self.__class__.__name__))

        debug('  tempfile.tempdir=%r', tempfile.tempdir)

        CommandLineParser.parse(self, argv[2:])
        self.prepare()

        if self.record:
            self.record = False

            record_argv = [argv[0], argv[1], str(self._options), ' '.join(self.fieldnames)]
            ifile, ofile = self._prepare_recording(record_argv, ifile, ofile)
            self._record_writer.ofile = ofile
            ifile.record(str(self._input_header), '\n\n')

        if self.show_configuration:
            self.write_info(self.name + ' command configuration: ' + str(self._configuration))

        return ifile  # wrapped, if self.record is True 
Example 10
Project: sic   Author: Yanixos   File: sandbox.py    GNU General Public License v3.0 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    if not os.path.isdir(replacement):
        os.makedirs(replacement)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 11
Project: bigquerylayers   Author: smandaric   File: sandbox.py    GNU General Public License v3.0 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    pkg_resources.py31compat.makedirs(replacement, exist_ok=True)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 12
Project: AshsSDK   Author: thehappydinoa   File: sandbox.py    MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    pkg_resources.py31compat.makedirs(replacement, exist_ok=True)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 13
Project: calmjs   Author: calmjs   File: test_testing.py    GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        self.tmpdir = realpath(tempfile.mkdtemp())
        tempfile.tempdir = self.tmpdir 
Example 14
Project: calmjs   Author: calmjs   File: test_testing.py    GNU General Public License v2.0 5 votes vote down vote up
def tearDown(self):
        # This is safe - the module will just call gettempdir() again
        tempfile.tempdir = None
        rmtree(self.tmpdir) 
Example 15
Project: Repobot   Author: Desgard   File: sandbox.py    MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    if not os.path.isdir(replacement):
        os.makedirs(replacement)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 16
Project: misp42splunk   Author: remg427   File: search_command.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _prepare_protocol_v1(self, argv, ifile, ofile):

        debug = environment.splunklib_logger.debug

        # Provide as much context as possible in advance of parsing the command line and preparing for execution

        self._input_header.read(ifile)
        self._protocol_version = 1
        self._map_metadata(argv)

        debug('  metadata=%r, input_header=%r', self._metadata, self._input_header)

        try:
            tempfile.tempdir = self._metadata.searchinfo.dispatch_dir
        except AttributeError:
            raise RuntimeError('{}.metadata.searchinfo.dispatch_dir is undefined'.format(self.__class__.__name__))

        debug('  tempfile.tempdir=%r', tempfile.tempdir)

        CommandLineParser.parse(self, argv[2:])
        self.prepare()

        if self.record:
            self.record = False

            record_argv = [argv[0], argv[1], str(self._options), ' '.join(self.fieldnames)]
            ifile, ofile = self._prepare_recording(record_argv, ifile, ofile)
            self._record_writer.ofile = ofile
            ifile.record(str(self._input_header), '\n\n')

        if self.show_configuration:
            self.write_info(self.name + ' command configuration: ' + str(self._configuration))

        return ifile  # wrapped, if self.record is True 
Example 17
Project: misp42splunk   Author: remg427   File: search_command.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _prepare_protocol_v1(self, argv, ifile, ofile):

        debug = environment.splunklib_logger.debug

        # Provide as much context as possible in advance of parsing the command line and preparing for execution

        self._input_header.read(ifile)
        self._protocol_version = 1
        self._map_metadata(argv)

        debug('  metadata=%r, input_header=%r', self._metadata, self._input_header)

        try:
            tempfile.tempdir = self._metadata.searchinfo.dispatch_dir
        except AttributeError:
            raise RuntimeError('{}.metadata.searchinfo.dispatch_dir is undefined'.format(self.__class__.__name__))

        debug('  tempfile.tempdir=%r', tempfile.tempdir)

        CommandLineParser.parse(self, argv[2:])
        self.prepare()

        if self.record:
            self.record = False

            record_argv = [argv[0], argv[1], str(self._options), ' '.join(self.fieldnames)]
            ifile, ofile = self._prepare_recording(record_argv, ifile, ofile)
            self._record_writer.ofile = ofile
            ifile.record(str(self._input_header), '\n\n')

        if self.show_configuration:
            self.write_info(self.name + ' command configuration: ' + str(self._configuration))

        return ifile  # wrapped, if self.record is True 
Example 18
Project: misp42splunk   Author: remg427   File: search_command.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _prepare_protocol_v1(self, argv, ifile, ofile):

        debug = environment.splunklib_logger.debug

        # Provide as much context as possible in advance of parsing the command line and preparing for execution

        self._input_header.read(ifile)
        self._protocol_version = 1
        self._map_metadata(argv)

        debug('  metadata=%r, input_header=%r', self._metadata, self._input_header)

        try:
            tempfile.tempdir = self._metadata.searchinfo.dispatch_dir
        except AttributeError:
            raise RuntimeError('{}.metadata.searchinfo.dispatch_dir is undefined'.format(self.__class__.__name__))

        debug('  tempfile.tempdir=%r', tempfile.tempdir)

        CommandLineParser.parse(self, argv[2:])
        self.prepare()

        if self.record:
            self.record = False

            record_argv = [argv[0], argv[1], str(self._options), ' '.join(self.fieldnames)]
            ifile, ofile = self._prepare_recording(record_argv, ifile, ofile)
            self._record_writer.ofile = ofile
            ifile.record(str(self._input_header), '\n\n')

        if self.show_configuration:
            self.write_info(self.name + ' command configuration: ' + str(self._configuration))

        return ifile  # wrapped, if self.record is True 
Example 19
Project: STM   Author: matematik7   File: test_processor.py    MIT License 5 votes vote down vote up
def setUp(self):
        self.tmpfolder = path.join(tempdir, 'stm-test/')
        
        self.conf = Configuration()
        self.conf.folder = self.tmpfolder
        self.conf.cropMode = 'none' 
Example 20
Project: STM   Author: matematik7   File: test_load_save.py    MIT License 5 votes vote down vote up
def setUp(self):
        self.tempfile = path.join(tempdir, 'stm-test.png')
        self.conf = Configuration()
        self.conf.output = self.tempfile
        self.conf.cropMode = 'none' 
Example 21
Project: SplunkVersionControl   Author: gjanders   File: search_command.py    Apache License 2.0 5 votes vote down vote up
def _prepare_protocol_v1(self, argv, ifile, ofile):

        debug = environment.splunklib_logger.debug

        # Provide as much context as possible in advance of parsing the command line and preparing for execution

        self._input_header.read(ifile)
        self._protocol_version = 1
        self._map_metadata(argv)

        debug('  metadata=%r, input_header=%r', self._metadata, self._input_header)

        try:
            tempfile.tempdir = self._metadata.searchinfo.dispatch_dir
        except AttributeError:
            raise RuntimeError('{}.metadata.searchinfo.dispatch_dir is undefined'.format(self.__class__.__name__))

        debug('  tempfile.tempdir=%r', tempfile.tempdir)

        CommandLineParser.parse(self, argv[2:])
        self.prepare()

        if self.record:
            self.record = False

            record_argv = [argv[0], argv[1], str(self._options), ' '.join(self.fieldnames)]
            ifile, ofile = self._prepare_recording(record_argv, ifile, ofile)
            self._record_writer.ofile = ofile
            ifile.record(str(self._input_header), '\n\n')

        if self.show_configuration:
            self.write_info(self.name + ' command configuration: ' + str(self._configuration))

        return ifile  # wrapped, if self.record is True 
Example 22
Project: NiujiaoDebugger   Author: MrSrc   File: test_tempfile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_exports(self):
        # There are no surprising symbols in the tempfile module
        dict = tempfile.__dict__

        expected = {
            "NamedTemporaryFile" : 1,
            "TemporaryFile" : 1,
            "mkstemp" : 1,
            "mkdtemp" : 1,
            "mktemp" : 1,
            "TMP_MAX" : 1,
            "gettempprefix" : 1,
            "gettempprefixb" : 1,
            "gettempdir" : 1,
            "gettempdirb" : 1,
            "tempdir" : 1,
            "template" : 1,
            "SpooledTemporaryFile" : 1,
            "TemporaryDirectory" : 1,
        }

        unexp = []
        for key in dict:
            if key[0] != '_' and key not in expected:
                unexp.append(key)
        self.assertTrue(len(unexp) == 0,
                        "unexpected keys: %s" % unexp) 
Example 23
Project: NiujiaoDebugger   Author: MrSrc   File: test_tempfile.py    GNU General Public License v3.0 5 votes vote down vote up
def _inside_empty_temp_dir():
    dir = tempfile.mkdtemp()
    try:
        with support.swap_attr(tempfile, 'tempdir', dir):
            yield
    finally:
        support.rmtree(dir) 
Example 24
Project: NiujiaoDebugger   Author: MrSrc   File: test_tempfile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_read_only_directory(self):
        with _inside_empty_temp_dir():
            oldmode = mode = os.stat(tempfile.tempdir).st_mode
            mode &= ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
            os.chmod(tempfile.tempdir, mode)
            try:
                if os.access(tempfile.tempdir, os.W_OK):
                    self.skipTest("can't set the directory read-only")
                with self.assertRaises(PermissionError):
                    self.make_temp()
                self.assertEqual(os.listdir(tempfile.tempdir), [])
            finally:
                os.chmod(tempfile.tempdir, oldmode) 
Example 25
Project: NiujiaoDebugger   Author: MrSrc   File: test_tempfile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_nonexisting_directory(self):
        with _inside_empty_temp_dir():
            tempdir = os.path.join(tempfile.tempdir, 'nonexistent')
            with support.swap_attr(tempfile, 'tempdir', tempdir):
                with self.assertRaises(FileNotFoundError):
                    self.make_temp() 
Example 26
Project: NiujiaoDebugger   Author: MrSrc   File: test_tempfile.py    GNU General Public License v3.0 5 votes vote down vote up
def test_non_directory(self):
        with _inside_empty_temp_dir():
            tempdir = os.path.join(tempfile.tempdir, 'file')
            open(tempdir, 'wb').close()
            with support.swap_attr(tempfile, 'tempdir', tempdir):
                with self.assertRaises((NotADirectoryError, FileNotFoundError)):
                    self.make_temp() 
Example 27
Project: threatdetectionservice   Author: flyballlabs   File: sandbox.py    Apache License 2.0 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    if not os.path.isdir(replacement):
        os.makedirs(replacement)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 28
Project: aws-cfn-plex   Author: lordmuffin   File: sandbox.py    MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    if not os.path.isdir(replacement):
        os.makedirs(replacement)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 29
Project: jbox   Author: jpush   File: sandbox.py    MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    if not os.path.isdir(replacement):
        os.makedirs(replacement)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 30
Project: Alexa-Ecovacs   Author: EtienneMD   File: sandbox.py    MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    pkg_resources.py31compat.makedirs(replacement, exist_ok=True)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 31
Project: neo4j-social-network   Author: bestvibes   File: sandbox.py    MIT License 5 votes vote down vote up
def run_setup(setup_script, args):
    """Run a distutils setup script, sandboxed in its directory"""
    old_dir = os.getcwd()
    save_argv = sys.argv[:]
    save_path = sys.path[:]
    setup_dir = os.path.abspath(os.path.dirname(setup_script))
    temp_dir = os.path.join(setup_dir,'temp')
    if not os.path.isdir(temp_dir): os.makedirs(temp_dir)
    save_tmp = tempfile.tempdir
    save_modules = sys.modules.copy()
    pr_state = pkg_resources.__getstate__()
    try:
        tempfile.tempdir = temp_dir
        os.chdir(setup_dir)
        try:
            sys.argv[:] = [setup_script]+list(args)
            sys.path.insert(0, setup_dir)
            DirectorySandbox(setup_dir).run(
                lambda: execfile(
                    "setup.py",
                    {'__file__':setup_script, '__name__':'__main__'}
                )
            )
        except SystemExit, v:
            if v.args and v.args[0]:
                raise
            # Normal exit, just return
    finally:
        pkg_resources.__setstate__(pr_state)
        sys.modules.update(save_modules)
        for key in list(sys.modules):
            if key not in save_modules: del sys.modules[key]
        os.chdir(old_dir)
        sys.path[:] = save_path
        sys.argv[:] = save_argv
        tempfile.tempdir = save_tmp 
Example 32
Project: neo4j-social-network   Author: bestvibes   File: sandbox.py    MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    if not os.path.isdir(replacement):
        os.makedirs(replacement)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 33
Project: beam   Author: axbaretto   File: sandbox.py    Apache License 2.0 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    if not os.path.isdir(replacement):
        os.makedirs(replacement)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 34
Project: chord-sequence-chooser   Author: bwetherfield   File: sandbox.py    MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    pkg_resources.py31compat.makedirs(replacement, exist_ok=True)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 35
Project: centreon-discovery   Author: Centreon-Community   File: sandbox.py    GNU General Public License v2.0 5 votes vote down vote up
def run_setup(setup_script, args):
    """Run a distutils setup script, sandboxed in its directory"""
    old_dir = os.getcwd()
    save_argv = sys.argv[:]
    save_path = sys.path[:]
    setup_dir = os.path.abspath(os.path.dirname(setup_script))
    temp_dir = os.path.join(setup_dir,'temp')
    if not os.path.isdir(temp_dir): os.makedirs(temp_dir)
    save_tmp = tempfile.tempdir
    save_modules = sys.modules.copy()
    pr_state = pkg_resources.__getstate__()
    try:
        tempfile.tempdir = temp_dir; os.chdir(setup_dir)
        try:
            sys.argv[:] = [setup_script]+list(args)
            sys.path.insert(0, setup_dir)
            # reset to include setup dir, w/clean callback list
            working_set.__init__()  
            working_set.callbacks.append(lambda dist:dist.activate())
            DirectorySandbox(setup_dir).run(
                lambda: execfile(
                    "setup.py",
                    {'__file__':setup_script, '__name__':'__main__'}
                )
            )
        except SystemExit, v:
            if v.args and v.args[0]:
                raise
            # Normal exit, just return
    finally:
        pkg_resources.__setstate__(pr_state)
        sys.modules.update(save_modules)
        for key in list(sys.modules):
            if key not in save_modules: del sys.modules[key]
        os.chdir(old_dir)
        sys.path[:] = save_path
        sys.argv[:] = save_argv
        tempfile.tempdir = save_tmp 
Example 36
Project: grand_central   Author: amiracle   File: search_command.py    MIT License 5 votes vote down vote up
def _prepare_protocol_v1(self, argv, ifile, ofile):

        debug = environment.splunklib_logger.debug

        # Provide as much context as possible in advance of parsing the command line and preparing for execution

        self._input_header.read(ifile)
        self._protocol_version = 1
        self._map_metadata(argv)

        debug('  metadata=%r, input_header=%r', self._metadata, self._input_header)

        try:
            tempfile.tempdir = self._metadata.searchinfo.dispatch_dir
        except AttributeError:
            raise RuntimeError('{}.metadata.searchinfo.dispatch_dir is undefined'.format(self.__class__.__name__))

        debug('  tempfile.tempdir=%r', tempfile.tempdir)

        CommandLineParser.parse(self, argv[2:])
        self.prepare()

        if self.record:
            self.record = False

            record_argv = [argv[0], argv[1], str(self._options), ' '.join(self.fieldnames)]
            ifile, ofile = self._prepare_recording(record_argv, ifile, ofile)
            self._record_writer.ofile = ofile
            ifile.record(str(self._input_header), '\n\n')

        if self.show_configuration:
            self.write_info(self.name + ' command configuration: ' + str(self._configuration))

        return ifile  # wrapped, if self.record is True 
Example 37
Project: SplunkForPCAP   Author: DanielSchwartz1   File: search_command.py    MIT License 5 votes vote down vote up
def _prepare_protocol_v1(self, argv, ifile, ofile):

        debug = environment.splunklib_logger.debug

        # Provide as much context as possible in advance of parsing the command line and preparing for execution

        self._input_header.read(ifile)
        self._protocol_version = 1
        self._map_metadata(argv)

        debug('  metadata=%r, input_header=%r', self._metadata, self._input_header)

        try:
            tempfile.tempdir = self._metadata.searchinfo.dispatch_dir
        except AttributeError:
            raise RuntimeError('{}.metadata.searchinfo.dispatch_dir is undefined'.format(self.__class__.__name__))

        debug('  tempfile.tempdir=%r', tempfile.tempdir)

        CommandLineParser.parse(self, argv[2:])
        self.prepare()

        if self.record:
            self.record = False

            record_argv = [argv[0], argv[1], str(self._options), ' '.join(self.fieldnames)]
            ifile, ofile = self._prepare_recording(record_argv, ifile, ofile)
            self._record_writer.ofile = ofile
            ifile.record(str(self._input_header), '\n\n')

        if self.show_configuration:
            self.write_info(self.name + ' command configuration: ' + str(self._configuration))

        return ifile  # wrapped, if self.record is True 
Example 38
Project: AneMo   Author: jspargo   File: sandbox.py    GNU General Public License v2.0 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    if not os.path.isdir(replacement):
        os.makedirs(replacement)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 39
Project: Mahjong-Solitaire   Author: MEASHY   File: sandbox.py    MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    if not os.path.isdir(replacement):
        os.makedirs(replacement)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 40
Project: Mahjong-Solitaire   Author: MEASHY   File: sandbox.py    MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    if not os.path.isdir(replacement):
        os.makedirs(replacement)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 41
Project: oa_qian   Author: sunqb   File: sandbox.py    Apache License 2.0 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    if not os.path.isdir(replacement):
        os.makedirs(replacement)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 42
Project: pyquarkchain   Author: QuarkChain   File: bootnode_health_check.py    MIT License 5 votes vote down vote up
def main():
    if "EMAIL_FROM_ADDRESS" not in os.environ:
        raise ValueError("EMAIL_FROM_ADDRESS not found in environment variables")
    if "PASSWORD" not in os.environ:
        raise ValueError("PASSWORD not found in environment variables")
    if "EMAIL_TO_ADDRESS" not in os.environ:
        raise ValueError("EMAIL_TO_ADDRESS not found in environment variables")

    os.chdir(os.path.dirname("../../quarkchain/cluster/"))
    parser = argparse.ArgumentParser()
    ClusterConfig.attach_arguments(parser)
    args = parser.parse_args()
    config = ClusterConfig.create_from_args(args)

    # creat a config tempfile for health check, which is a copy of the original config file
    tempfile.tempdir = "../../mainnet/singularity/"
    fd, config.json_filepath = tempfile.mkstemp()
    with os.fdopen(fd, "w") as tmp:
        tmp.write(config.to_json())
    print("Cluster config file: {}".format(config.json_filepath))
    print(config.to_json())

    cluster = HealthCheckCluster(config)
    bootstrap_nodes = config.P2P.BOOT_NODES.split(",")
    count = 0

    while True:
        bash_command_revised_config = (
            "QKC_CONFIG="
            + config.json_filepath
            + " python3 ../../quarkchain/tools/config_p2p.py --bootnodes "
            + bootstrap_nodes[count]
        )
        os.system(bash_command_revised_config)
        print("Start Bootstrap With " + bootstrap_nodes[count])
        cluster.start_and_loop()
        time.sleep(100)
        count = (count + 1) % len(bootstrap_nodes) 
Example 43
Project: pyontutils   Author: tgbugs   File: scig.py    MIT License 5 votes vote down vote up
def write_import_chain(self, location=tempfile.tempdir):
        html = self.make_html()
        if not html:
            self.path = f'{tempfile.tempdir}/noimport.html'
        else:
            self.name = Path(next(iter(self.tree.keys()))).name
            self.path = Path(location, f'{self.name}-import-closure.html')

        with open(self.path.as_posix(), 'wt') as f:
            f.write(html)  # much more readable 
Example 44
Project: pyontutils   Author: tgbugs   File: hierarchies.py    MIT License 5 votes vote down vote up
def _main():
    rtco = 'http://purl.org/sig/ont/fma/constitutional_part_of'
    rtro = 'http://purl.org/sig/ont/fma/regional_part_of'
    #rtc = 'http://purl.org/sig/ont/fma/constitutional_part'.replace('/','%2F')  # FIXME the sub/pred relation is switched :/
    #rtr = 'http://purl.org/sig/ont/fma/regional_part'.replace('/','%2F')
    json_co = sgg_local.getEdges(rtco, limit=9999999999)
    json_ro = sgg_local.getEdges(rtro, limit=9999999999)
    #json_c = g.getEdges(rtc, limit=9999999999)
    #json_r = g.getEdges(rtr, limit=9999999999)
    #inv_edges(json_c)
    #inv_edges(json_r)

    json = json_ro
    #json['nodes'].extend(json_co['nodes'])
    #json['edges'].extend(json_co['edges'])

    #json['nodes'].extend(json_c['nodes'])
    #json['edges'].extend(json_c['edges'])
    #json['nodes'].extend(json_r['nodes'])
    #json['edges'].extend(json_r['edges'])
    #embed()


    #fma = Query('FMA:50801', 'None', 'INCOMING', 20)
    fma = Query('FMA:61817', 'None', 'INCOMING', 20)  # Cerebral hemisphere
    fma_tree, fma_extra = creatTree(*fma, json=json)
    with open(f'{tempfile.tempdir}/rc_combo_tree', 'wt') as f: f.write(str(fma_tree))

    embed() 
Example 45
Project: pyontutils   Author: tgbugs   File: test_config.py    MIT License 5 votes vote down vote up
def test_set_git_local_base(self):
        git_local_base_1 = devconfig.git_local_base
        ontology_local_1 = devconfig.ontology_local_repo
        v2 = '{tempfile.tempdir}/not-a-thing'
        devconfig.git_local_base = v2
        v3 = devconfig.git_local_base
        maybe_ontology_local_after_change_base = devconfig._maybe_repo
        devconfig.git_local_base = git_local_base_1
        assert ontology_local_1 != maybe_ontology_local_after_change_base
        # we can only check against _maybe_repo because
        # v2 does not exist and thus will not propagate
        assert git_local_base_1 != v2
        assert git_local_base_1 != v3
        assert v2 == v3
        assert git_local_base_1 == devconfig.git_local_base 
Example 46
Project: pyontutils   Author: tgbugs   File: test_config.py    MIT License 5 votes vote down vote up
def test_set_scigraph_api(self):
        v1 = devconfig.scigraph_api
        v2 = '{tempfile.tempdir}/not-a-thing'
        devconfig.scigraph_api = v2
        v3 = devconfig.scigraph_api
        devconfig.scigraph_api = v1
        assert v1 != v2
        assert v1 != v3
        assert v2 == v3
        assert v1 == devconfig.scigraph_api 
Example 47
Project: pyontutils   Author: tgbugs   File: test_config.py    MIT License 5 votes vote down vote up
def test_set_secrets_file(self):
        v1 = devconfig.secrets_file
        v2 = '{tempfile.tempdir}/not-a-thing'
        devconfig.secrets_file = v2
        v3 = devconfig.secrets_file
        devconfig.secrets_file = v1
        assert v1 != v2
        assert v1 != v3
        assert v2 == v3
        assert v1 == devconfig.secrets_file 
Example 48
Project: python-netsurv   Author: sofia-netsurv   File: sandbox.py    MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    if not os.path.isdir(replacement):
        os.makedirs(replacement)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 49
Project: python-netsurv   Author: sofia-netsurv   File: sandbox.py    MIT License 5 votes vote down vote up
def override_temp(replacement):
    """
    Monkey-patch tempfile.tempdir with replacement, ensuring it exists
    """
    if not os.path.isdir(replacement):
        os.makedirs(replacement)

    saved = tempfile.tempdir

    tempfile.tempdir = replacement

    try:
        yield
    finally:
        tempfile.tempdir = saved 
Example 50
Project: scratchdir   Author: ahawker   File: scratchdir.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, prefix: str = '', suffix: str = '.scratchdir', base: typing.Optional[str] = None,
                 root: typing.Optional[str] = tempfile.tempdir, wd: str = DEFAULT_WD) -> None:
        self.prefix = prefix
        self.suffix = suffix
        self.base = base
        self.root = root
        self.wd = wd