Python sys.path() Examples

The following are 30 code examples of sys.path(). 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 sys , or try the search function .
Example #1
Source File: conf.py    From python-template with Apache License 2.0 6 votes vote down vote up
def run_apidoc(_):
    here = os.path.dirname(__file__)
    out = os.path.abspath(os.path.join(here, 'apidocs'))
    src = os.path.abspath(os.path.join(here, '..', '{{ cookiecutter.project_slug }}'))

    ignore_paths = []

    argv = [
        "-f",
        "-T",
        "-e",
        "-M",
        "-o", out,
        src
    ] + ignore_paths

    try:
        # Sphinx 1.7+
        from sphinx.ext import apidoc
        apidoc.main(argv)
    except ImportError:
        # Sphinx 1.6 (and earlier)
        from sphinx import apidoc
        argv.insert(0, apidoc.__file__)
        apidoc.main(argv) 
Example #2
Source File: test_Export.py    From URS with MIT License 6 votes vote down vote up
def test_write_csv(self):
        filename = os.path.join(sys.path[0], "test_csv_writing.csv")
        overview = {
            "this": [1, 2],
            "is": [3, 4],
            "a": [5, 6],
            "test": [7, 8]}

        Export.Export._write_csv(filename, overview)

        with open(filename, "r") as test_csv:
            reader = csv.reader(test_csv)
            test_dict = dict((header, []) for header in next(reader))
            for row in reader:
                for row_index, key in enumerate(test_dict.keys()):
                    test_dict[key].append(int(row[row_index]))

        assert test_dict == overview
        os.remove(filename) 
Example #3
Source File: wspbus.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _extend_pythonpath(env):
        """Prepend current working dir to PATH environment variable if needed.

        If sys.path[0] is an empty string, the interpreter was likely
        invoked with -m and the effective path is about to change on
        re-exec.  Add the current directory to $PYTHONPATH to ensure
        that the new process sees the same path.

        This issue cannot be addressed in the general case because
        Python cannot reliably reconstruct the
        original command line (http://bugs.python.org/issue14208).

        (This idea filched from tornado.autoreload)
        """
        path_prefix = '.' + os.pathsep
        existing_path = env.get('PYTHONPATH', '')
        needs_patch = (
            sys.path[0] == '' and
            not existing_path.startswith(path_prefix)
        )

        if needs_patch:
            env['PYTHONPATH'] = path_prefix + existing_path 
Example #4
Source File: _cpmodpy.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def start(self):
        opts = ''.join(['    PythonOption %s %s\n' % (k, v)
                        for k, v in self.opts])
        conf_data = self.template % {'port': self.port,
                                     'loc': self.loc,
                                     'opts': opts,
                                     'handler': self.handler,
                                     }

        mpconf = os.path.join(os.path.dirname(__file__), 'cpmodpy.conf')
        f = open(mpconf, 'wb')
        try:
            f.write(conf_data)
        finally:
            f.close()

        response = read_process(self.apache_path, '-k start -f %s' % mpconf)
        self.ready = True
        return response 
Example #5
Source File: _cpmodpy.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def read_process(cmd, args=''):
    fullcmd = '%s %s' % (cmd, args)
    pipeout = popen(fullcmd)
    try:
        firstline = pipeout.readline()
        cmd_not_found = re.search(
            b'(not recognized|No such file|not found)',
            firstline,
            re.IGNORECASE
        )
        if cmd_not_found:
            raise IOError('%s must be on your system path.' % cmd)
        output = firstline + pipeout.read()
    finally:
        pipeout.close()
    return output 
Example #6
Source File: client.py    From iSDX with Apache License 2.0 6 votes vote down vote up
def _receiver(conn,stdout):

    while True:
        try:
            line = conn.recv()

            if line == "":
                continue

            _write(stdout, line)
            ''' example: announce route 1.2.3.4 next-hop 5.6.7.8 as-path [ 100 200 ] '''

            recvLogger.debug(line)

        except:
            pass 
Example #7
Source File: workflow.py    From wechat-alfred-workflow with MIT License 6 votes vote down vote up
def _delete_directory_contents(self, dirpath, filter_func):
        """Delete all files in a directory.

        :param dirpath: path to directory to clear
        :type dirpath: ``unicode`` or ``str``
        :param filter_func function to determine whether a file shall be
            deleted or not.
        :type filter_func ``callable``

        """
        if os.path.exists(dirpath):
            for filename in os.listdir(dirpath):
                if not filter_func(filename):
                    continue
                path = os.path.join(dirpath, filename)
                if os.path.isdir(path):
                    shutil.rmtree(path)
                else:
                    os.unlink(path)
                self.logger.debug('deleted : %r', path) 
Example #8
Source File: venv_update.py    From mealpy with MIT License 6 votes vote down vote up
def has_system_site_packages(interpreter):
    # TODO: unit-test
    system_site_packages = check_output((
        interpreter,
        '-c',
        # stolen directly from virtualenv's site.py
        """\
import site, os.path
print(
    0
    if os.path.exists(
        os.path.join(os.path.dirname(site.__file__), 'no-global-site-packages.txt')
    ) else
    1
)"""
    ))
    system_site_packages = int(system_site_packages)
    assert system_site_packages in (0, 1)
    return bool(system_site_packages) 
Example #9
Source File: arproxy.py    From iSDX with Apache License 2.0 6 votes vote down vote up
def main():
    global arpListener, config

    parser = argparse.ArgumentParser()
    parser.add_argument('dir', help='the directory of the example')
    args = parser.parse_args()

    # locate config file
    config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),"..","examples",args.dir,"config","sdx_global.cfg")

    logger.info("Reading config file %s", config_file)
    config = parse_config(config_file)

    logger.info("Starting ARP Listener")
    arpListener = ArpListener()
    ap_thread = Thread(target=arpListener.start)
    ap_thread.start()

    # start pctrl listener in foreground
    logger.info("Starting PCTRL Listener")
    pctrlListener = PctrlListener()
    pctrlListener.start() 
Example #10
Source File: workflow.py    From wechat-alfred-workflow with MIT License 6 votes vote down vote up
def cache_data(self, name, data):
        """Save ``data`` to cache under ``name``.

        If ``data`` is ``None``, the corresponding cache file will be
        deleted.

        :param name: name of datastore
        :param data: data to store. This may be any object supported by
                the cache serializer

        """
        serializer = manager.serializer(self.cache_serializer)

        cache_path = self.cachefile('%s.%s' % (name, self.cache_serializer))

        if data is None:
            if os.path.exists(cache_path):
                os.unlink(cache_path)
                self.logger.debug('deleted cache file: %s', cache_path)
            return

        with atomic_writer(cache_path, 'wb') as file_obj:
            serializer.dump(data, file_obj)

        self.logger.debug('cached data: %s', cache_path) 
Example #11
Source File: test-distro.py    From multibootusb with GNU General Public License v2.0 6 votes vote down vote up
def test_distro_detection(self):
        def os_path_exists(f):
            if f.endswith('multibootusb.log'):
                return False
            return True
        os_path_exists_mock = MM()
        log_mock = MM()
        @patch('os.path.exists', os_path_exists)
        @patch('scripts.distro.log', log_mock)
        def _():
            fn = distro.detect_iso_from_file_list
            assert fn(['BOOT.wim', 'Sources']) == 'Windows'
            assert fn(['BOOT.wim', 'Sause']) is None
            assert fn(['config.isoclient', 'foo']) == 'opensuse'
            assert fn(['bar', 'dban', 'foo']) == 'slitaz'
            assert fn(['memtest.img']) == 'memtest'
            assert fn(['mt86.png','isolinux']) == 'raw_iso'
            assert fn(['menu.lst']) == 'grub4dos'
            assert fn(['bootwiz.cfg', 'bootmenu_logo.png']) == \
                'grub4dos_iso'
        _() 
Example #12
Source File: test_testing.py    From calmjs with GNU General Public License v2.0 6 votes vote down vote up
def test_rmtree_test(self):
        path = mkdtemp(self)
        utils.rmtree(path)
        self.assertFalse(exists(path))
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            utils.rmtree(path)
            self.assertFalse(w)

        utils.stub_item_attr_value(
            self, utils, 'rmtree_', utils.fake_error(IOError))
        path2 = mkdtemp(self)

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            utils.rmtree(path2)
            self.assertIn("rmtree failed to remove", str(w[-1].message)) 
Example #13
Source File: server.py    From The-chat-room with MIT License 6 votes vote down vote up
def cd(self, message, conn):
        message = message.split()[1]                          # 截取目录名
        # 如果是新连接或者下载上传文件后的发送则 不切换 只将当前工作目录发送过去
        if message != 'same':
            f = r'./' + message
            os.chdir(f)
        # path = ''
        path = os.getcwd().split('\\')                        # 当前工作目录
        for i in range(len(path)):
            if path[i] == 'resources':
                break
        pat = ''
        for j in range(i, len(path)):
            pat = pat + path[j] + ' '
        pat = '\\'.join(pat.split())
        # 如果切换目录超出范围则退回切换前目录
        if 'resources' not in path:
            f = r'./resources'
            os.chdir(f)
            pat = 'resources'
        conn.send(pat.encode())

    # 判断输入的命令并执行对应的函数 
Example #14
Source File: demo_letter_duvenaud.py    From nmp_qc with MIT License 6 votes vote down vote up
def plot_examples(data_loader, model, epoch, plotter, ind = [0, 10, 20]):

    # switch to evaluate mode
    model.eval()

    for i, (g, h, e, target) in enumerate(data_loader):
        if i in ind:
            subfolder_path = 'batch_' + str(i) + '_t_' + str(int(target[0][0])) + '/epoch_' + str(epoch) + '/'
            if not os.path.isdir(args.plotPath + subfolder_path):
                os.makedirs(args.plotPath + subfolder_path)

            num_nodes = torch.sum(torch.sum(torch.abs(h[0, :, :]), 1) > 0)
            am = g[0, 0:num_nodes, 0:num_nodes].numpy()
            pos = h[0, 0:num_nodes, :].numpy()

            plotter.plot_graph(am, position=pos, fig_name=subfolder_path+str(i) + '_input.png')

            # Prepare input data
            if args.cuda:
                g, h, e, target = g.cuda(), h.cuda(), e.cuda(), target.cuda()
            g, h, e, target = Variable(g), Variable(h), Variable(e), Variable(target)

            # Compute output
            model(g, h, e, lambda cls, id: plotter.plot_graph(am, position=pos, cls=cls,
                                                          fig_name=subfolder_path+ id)) 
Example #15
Source File: workflow.py    From wechat-alfred-workflow with MIT License 6 votes vote down vote up
def cachedir(self):
        """Path to workflow's cache directory.

        The cache directory is a subdirectory of Alfred's own cache directory
        in ``~/Library/Caches``. The full path is:

        ``~/Library/Caches/com.runningwithcrayons.Alfred-X/Workflow Data/<bundle id>``

        ``Alfred-X`` may be ``Alfred-2`` or ``Alfred-3``.

        :returns: full path to workflow's cache directory
        :rtype: ``unicode``

        """
        if self.alfred_env.get('workflow_cache'):
            dirpath = self.alfred_env.get('workflow_cache')

        else:
            dirpath = self._default_cachedir

        return self._create(dirpath) 
Example #16
Source File: services.py    From bioservices with GNU General Public License v3.0 5 votes vote down vote up
def getUserAgent(self):
        #self.logging.info('getUserAgent: Begin')
        urllib_agent = 'Python-requests/%s' % requests.__version__
        #clientRevision = ''
        from bioservices import version
        clientVersion = version
        user_agent = 'BioServices/%s (bioservices.%s; Python %s; %s) %s' % (
            clientVersion, os.path.basename(__file__),
            platform.python_version(), platform.system(),
            urllib_agent
        )
        #self.logging.info('getUserAgent: user_agent: ' + user_agent)
        #self.logging.info('getUserAgent: End')
        return user_agent 
Example #17
Source File: base.py    From grimoirelab-sortinghat with GNU General Public License v3.0 5 votes vote down vote up
def datadir(filename):
    """Return the path of the file in the tests data dir"""

    return(os.path.join(__datadir__, filename)) 
Example #18
Source File: test_cmd_config.py    From grimoirelab-sortinghat with GNU General Public License v3.0 5 votes vote down vote up
def test_invalid_config_files(self):
        """Check whether it raises and error reading invalid configuration files"""

        # Test directory
        dirpath = os.path.expanduser('~')

        self.assertRaises(RuntimeError, self.cmd.set,
                          'db.user', 'value', dirpath) 
Example #19
Source File: test_cmd_unify.py    From grimoirelab-sortinghat with GNU General Public License v3.0 5 votes vote down vote up
def test_unify_no_success_no_recovery_mode(self, mock_merge_unique_identities):
        """Test command when the the recovery mode is not active and the execution isn't ok"""

        mock_merge_unique_identities.side_effect = Exception

        with unittest.mock.patch('sortinghat.cmd.unify.RecoveryFile.location') as mock_location:
            mock_location.return_value = self.recovery_path

            self.assertFalse(os.path.exists(self.recovery_path))
            with self.assertRaises(Exception):
                self.cmd.unify(matching='default')
            self.assertFalse(os.path.exists(self.recovery_path)) 
Example #20
Source File: test_Export.py    From URS with MIT License 5 votes vote down vote up
def test_write_json(self):
        filename = os.path.join(sys.path[0], "test_json_writing.json")
        overview = {
            'test_1': {'this': 1, 'is': 1, 'a': 1, 'test': 1},
            'test_2': {'this': 2, 'is': 2, 'a': 2, 'test': 2}
        }

        Export.Export._write_json(filename, overview)

        with open(filename, "r") as test_json:
            test_dict = json.load(test_json)

        assert test_dict == overview
        os.remove(filename) 
Example #21
Source File: services.py    From bioservices with GNU General Public License v3.0 5 votes vote down vote up
def delete_cache(self):
        cache_file = self.CACHE_NAME + '.sqlite'
        if os.path.exists(cache_file):
            msg = "You are about to delete this bioservices cache: %s. Proceed? (y/[n]) "
            res = input(msg % cache_file)
            if res == "y":
                os.remove(cache_file)
                self.logging.info("Removed cache")
            else:
                self.logging.info("Reply 'y' to delete the file") 
Example #22
Source File: _init_paths.py    From cascade-rcnn_Pytorch with MIT License 5 votes vote down vote up
def add_path(path):
    if path not in sys.path:
        sys.path.insert(0, path) 
Example #23
Source File: conf.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def get_routes(app, endpoint=None, order=None):
    endpoints = []
    for rule in app.url_map.iter_rules(endpoint):
        url_with_endpoint = (
            six.text_type(next(app.url_map.iter_rules(rule.endpoint))),
            rule.endpoint
        )
        if url_with_endpoint not in endpoints:
            endpoints.append(url_with_endpoint)
    if order == 'path':
        endpoints.sort()
    endpoints = [e for _, e in endpoints]
    for endpoint in endpoints:
        methodrules = {}
        for rule in app.url_map.iter_rules(endpoint):
            if rule.methods is None:
                methods = ['GET']
            else:
                methods = rule.methods.difference(['OPTIONS', 'HEAD'])
            prefix = getattr(rule, 'doc_prefix', '')
            path = prefix + sphinxcontrib.autohttp.flask_base.translate_werkzeug_rule(rule.rule)
            for method in methods:
                if method in methodrules:
                    methodrules[method].append(path)
                else:
                    methodrules[method] = [path]
        for method, paths in methodrules.items():
            yield method, paths, endpoint 
Example #24
Source File: venv_update.py    From mealpy with MIT License 5 votes vote down vote up
def user_cache_dir():
    # stolen from pip.utils.appdirs.user_cache_dir
    from os import getenv
    from os.path import expanduser
    return getenv('XDG_CACHE_HOME', expanduser('~/.cache')) 
Example #25
Source File: conf.py    From bioservices with GNU General Public License v3.0 5 votes vote down vote up
def touch_example_backreferences(app, what, name, obj, options, lines):
    # generate empty examples files, so that we don't get
    # inclusion errors if there are no examples for a class / module
    examples_path = os.path.join(app.srcdir, "modules", "generated",
                                 "%s.examples" % name)
    if not os.path.exists(examples_path):
        # touch file
        os.makedirs(os.path.dirname(examples_path), exist_ok=True)
        open(examples_path, 'w').close()


# Add the 'copybutton' javascript, to hide/show the prompt in code
# examples 
Example #26
Source File: run.py    From find_forks with MIT License 5 votes vote down vote up
def main():
    """Main function to run as shell script."""
    loader = unittest.TestLoader()
    suite = loader.discover(path.abspath(path.dirname(__file__)), pattern='test_*.py')
    runner = unittest.TextTestRunner(buffer=True)
    runner.run(suite) 
Example #27
Source File: conf.py    From TOPFARM with GNU Affero General Public License v3.0 5 votes vote down vote up
def _sys_path_add(toadd=None):
    if toadd:
        distdir = os.path.dirname(os.path.dirname(__file__))
        sys.path = [distdir] + [os.path.join(distdir, p) for p in toadd] + sys.path 
Example #28
Source File: venv_update.py    From mealpy with MIT License 5 votes vote down vote up
def exec_scratch_virtualenv(args):
    """
    goals:
        - get any random site-packages off of the pythonpath
        - ensure we can import virtualenv
        - ensure that we're not using the interpreter that we may need to delete
        - idempotency: do nothing if the above goals are already met
    """
    scratch = Scratch()
    if not exists(scratch.python):
        run(('virtualenv', scratch.venv))

    if not exists(join(scratch.src, 'virtualenv.py')):
        scratch_python = venv_python(scratch.venv)
        # TODO: do we allow user-defined override of which version of virtualenv to install?
        tmp = scratch.src + '.tmp'
        run((scratch_python, '-m', 'pip.__main__', 'install', 'virtualenv', '--target', tmp))

        from os import rename
        rename(tmp, scratch.src)

    import sys
    from os.path import realpath
    # We want to compare the paths themselves as sometimes sys.path is the same
    # as scratch.venv, but with a suffix of bin/..
    if realpath(sys.prefix) != realpath(scratch.venv):
        # TODO-TEST: sometimes we would get a stale version of venv-update
        exec_((scratch.python, dotpy(__file__)) + args)  # never returns

    # TODO-TEST: the original venv-update's directory was on sys.path (when using symlinking)
    sys.path[0] = scratch.src 
Example #29
Source File: venv_update.py    From mealpy with MIT License 5 votes vote down vote up
def samefile(file1, file2):
    if not exists(file1) or not exists(file2):
        return False
    else:
        from os.path import samefile
        return samefile(file1, file2) 
Example #30
Source File: venv_update.py    From mealpy with MIT License 5 votes vote down vote up
def timid_relpath(arg):
    """convert an argument to a relative path, carefully"""
    # TODO-TEST: unit tests
    from os.path import isabs, relpath, sep
    if isabs(arg):
        result = relpath(arg)
        if result.count(sep) + 1 < arg.count(sep):
            return result

    return arg