Python sys.path() Examples

The following are 30 code examples for showing how to use sys.path(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module sys , or try the search function .

Example 1
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: 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 2
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: 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 3
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: 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 4
Project: cherrypy   Author: cherrypy   File: _cpmodpy.py    License: 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 5
Project: cherrypy   Author: cherrypy   File: _cpmodpy.py    License: 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 6
Project: cherrypy   Author: cherrypy   File: wspbus.py    License: 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 7
Project: iSDX   Author: sdn-ixp   File: client.py    License: 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 8
Project: iSDX   Author: sdn-ixp   File: arproxy.py    License: 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 9
Project: multibootusb   Author: mbusb   File: test-distro.py    License: 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 10
Project: nmp_qc   Author: priba   File: demo_letter_duvenaud.py    License: 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 11
Project: The-chat-room   Author: 11ze   File: server.py    License: 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 12
Project: python-template   Author: NLeSC   File: conf.py    License: 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 13
Project: mealpy   Author: edmundmok   File: venv_update.py    License: 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 14
Project: URS   Author: JosephLai241   File: test_Export.py    License: 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 15
Project: calmjs   Author: calmjs   File: test_testing.py    License: 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 16
Project: unicorn-hat-hd   Author: pimoroni   File: conf.py    License: MIT License 5 votes vote down vote up
def __init__(self, directive, name, indent=u''):
        # Monkey path the Method and Function documenters
        sphinx_app.add_autodocumenter(OutlineMethodDocumenter)
        sphinx_app.add_autodocumenter(OutlineFunctionDocumenter)
        autodoc.ModuleDocumenter.__init__(self, directive, name, indent) 
Example 17
Project: mutatest   Author: EvanKepner   File: conf.py    License: MIT License 5 votes vote down vote up
def read(*parts):
    """
    Build an absolute path from *parts* and and return the contents of the
    resulting file.  Assume UTF-8 encoding.
    """
    with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f:
        return f.read() 
Example 18
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: MIT License 5 votes vote down vote up
def __init__(self, filepath, defaults=None):
        """Create new :class:`Settings` object."""
        super(Settings, self).__init__()
        self._filepath = filepath
        self._nosave = False
        self._original = {}
        if os.path.exists(self._filepath):
            self._load()
        elif defaults:
            for key, val in defaults.items():
                self[key] = val
            self.save()  # save default settings 
Example 19
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: MIT License 5 votes vote down vote up
def _default_cachedir(self):
        """Alfred 2's default cache directory."""
        return os.path.join(
            os.path.expanduser(
                '~/Library/Caches/com.runningwithcrayons.Alfred-2/'
                'Workflow Data/'),
            self.bundleid) 
Example 20
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: MIT License 5 votes vote down vote up
def _default_datadir(self):
        """Alfred 2's default data directory."""
        return os.path.join(os.path.expanduser(
            '~/Library/Application Support/Alfred 2/Workflow Data/'),
            self.bundleid) 
Example 21
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: MIT License 5 votes vote down vote up
def workflowdir(self):
        """Path to workflow's root directory (where ``info.plist`` is).

        :returns: full path to workflow root directory
        :rtype: ``unicode``

        """
        if not self._workflowdir:
            # Try the working directory first, then the directory
            # the library is in. CWD will be the workflow root if
            # a workflow is being run in Alfred
            candidates = [
                os.path.abspath(os.getcwdu()),
                os.path.dirname(os.path.abspath(os.path.dirname(__file__)))]

            # climb the directory tree until we find `info.plist`
            for dirpath in candidates:

                # Ensure directory path is Unicode
                dirpath = self.decode(dirpath)

                while True:
                    if os.path.exists(os.path.join(dirpath, 'info.plist')):
                        self._workflowdir = dirpath
                        break

                    elif dirpath == '/':
                        # no `info.plist` found
                        break

                    # Check the parent directory
                    dirpath = os.path.dirname(dirpath)

                # No need to check other candidates
                if self._workflowdir:
                    break

            if not self._workflowdir:
                raise IOError("'info.plist' not found in directory tree")

        return self._workflowdir 
Example 22
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: MIT License 5 votes vote down vote up
def cachefile(self, filename):
        """Path to ``filename`` in workflow's cache directory.

        Return absolute path to ``filename`` within your workflow's
        :attr:`cache directory <Workflow.cachedir>`.

        :param filename: basename of file
        :type filename: ``unicode``
        :returns: full path to file within cache directory
        :rtype: ``unicode``

        """
        return os.path.join(self.cachedir, filename) 
Example 23
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: MIT License 5 votes vote down vote up
def datafile(self, filename):
        """Path to ``filename`` in workflow's data directory.

        Return absolute path to ``filename`` within your workflow's
        :attr:`data directory <Workflow.datadir>`.

        :param filename: basename of file
        :type filename: ``unicode``
        :returns: full path to file within data directory
        :rtype: ``unicode``

        """
        return os.path.join(self.datadir, filename) 
Example 24
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: MIT License 5 votes vote down vote up
def workflowfile(self, filename):
        """Return full path to ``filename`` in workflow's root directory.

        :param filename: basename of file
        :type filename: ``unicode``
        :returns: full path to file within data directory
        :rtype: ``unicode``

        """
        return os.path.join(self.workflowdir, filename) 
Example 25
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: MIT License 5 votes vote down vote up
def settings_path(self):
        """Path to settings file within workflow's data directory.

        :returns: path to ``settings.json`` file
        :rtype: ``unicode``

        """
        if not self._settings_path:
            self._settings_path = self.datafile('settings.json')
        return self._settings_path 
Example 26
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: MIT License 5 votes vote down vote up
def cached_data(self, name, data_func=None, max_age=60):
        """Return cached data if younger than ``max_age`` seconds.

        Retrieve data from cache or re-generate and re-cache data if
        stale/non-existant. If ``max_age`` is 0, return cached data no
        matter how old.

        :param name: name of datastore
        :param data_func: function to (re-)generate data.
        :type data_func: ``callable``
        :param max_age: maximum age of cached data in seconds
        :type max_age: ``int``
        :returns: cached data, return value of ``data_func`` or ``None``
            if ``data_func`` is not set

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

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

        if (age < max_age or max_age == 0) and os.path.exists(cache_path):

            with open(cache_path, 'rb') as file_obj:
                self.logger.debug('loading cached data: %s', cache_path)
                return serializer.load(file_obj)

        if not data_func:
            return None

        data = data_func()
        self.cache_data(name, data)

        return data 
Example 27
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: MIT License 5 votes vote down vote up
def cached_data_age(self, name):
        """Return age in seconds of cache `name` or 0 if cache doesn't exist.

        :param name: name of datastore
        :type name: ``unicode``
        :returns: age of datastore in seconds
        :rtype: ``int``

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

        if not os.path.exists(cache_path):
            return 0

        return time.time() - os.stat(cache_path).st_mtime 
Example 28
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: MIT License 5 votes vote down vote up
def start_update(self):
        """Check for update and download and install new workflow file.

        .. versionadded:: 1.9

        See :ref:`guide-updates` in the :ref:`user-manual` for detailed
        information on how to enable your workflow to update itself.

        :returns: ``True`` if an update is available and will be
            installed, else ``False``

        """
        import update

        github_slug = self._update_settings['github_slug']
        # version = self._update_settings['version']
        version = str(self.version)

        if not update.check_update(github_slug, version, self.prereleases):
            return False

        from background import run_in_background

        # update.py is adjacent to this file
        update_script = os.path.join(os.path.dirname(__file__),
                                     b'update.py')

        cmd = ['/usr/bin/python', update_script, 'install', github_slug,
               version]

        if self.prereleases:
            cmd.append('--prereleases')

        self.logger.debug('downloading update ...')
        run_in_background('__workflow_update_install', cmd)

        return True

    ####################################################################
    # Keychain password storage methods
    #################################################################### 
Example 29
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: MIT License 5 votes vote down vote up
def clear_settings(self):
        """Delete workflow's :attr:`settings_path`."""
        if os.path.exists(self.settings_path):
            os.unlink(self.settings_path)
            self.logger.debug('deleted : %r', self.settings_path) 
Example 30
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    License: MIT License 5 votes vote down vote up
def decode(self, text, encoding=None, normalization=None):
        """Return ``text`` as normalised unicode.

        If ``encoding`` and/or ``normalization`` is ``None``, the
        ``input_encoding``and ``normalization`` parameters passed to
        :class:`Workflow` are used.

        :param text: string
        :type text: encoded or Unicode string. If ``text`` is already a
            Unicode string, it will only be normalised.
        :param encoding: The text encoding to use to decode ``text`` to
            Unicode.
        :type encoding: ``unicode`` or ``None``
        :param normalization: The nomalisation form to apply to ``text``.
        :type normalization: ``unicode`` or ``None``
        :returns: decoded and normalised ``unicode``

        :class:`Workflow` uses "NFC" normalisation by default. This is the
        standard for Python and will work well with data from the web (via
        :mod:`~workflow.web` or :mod:`json`).

        macOS, on the other hand, uses "NFD" normalisation (nearly), so data
        coming from the system (e.g. via :mod:`subprocess` or
        :func:`os.listdir`/:mod:`os.path`) may not match. You should either
        normalise this data, too, or change the default normalisation used by
        :class:`Workflow`.

        """
        encoding = encoding or self._input_encoding
        normalization = normalization or self._normalizsation
        if not isinstance(text, unicode):
            text = unicode(text, encoding)
        return unicodedata.normalize(normalization, text)