當前位置: 首頁>>代碼示例>>Python>>正文


Python sys.path方法代碼示例

本文整理匯總了Python中sys.path方法的典型用法代碼示例。如果您正苦於以下問題:Python sys.path方法的具體用法?Python sys.path怎麽用?Python sys.path使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在sys的用法示例。


在下文中一共展示了sys.path方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: cachedir

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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) 
開發者ID:TKkk-iOSer,項目名稱:wechat-alfred-workflow,代碼行數:23,代碼來源:workflow.py

示例2: read_process

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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 
開發者ID:cherrypy,項目名稱:cherrypy,代碼行數:18,代碼來源:_cpmodpy.py

示例3: cache_data

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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) 
開發者ID:TKkk-iOSer,項目名稱:wechat-alfred-workflow,代碼行數:27,代碼來源:workflow.py

示例4: _delete_directory_contents

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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) 
開發者ID:TKkk-iOSer,項目名稱:wechat-alfred-workflow,代碼行數:22,代碼來源:workflow.py

示例5: start

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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 
開發者ID:cherrypy,項目名稱:cherrypy,代碼行數:21,代碼來源:_cpmodpy.py

示例6: _extend_pythonpath

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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 
開發者ID:cherrypy,項目名稱:cherrypy,代碼行數:25,代碼來源:wspbus.py

示例7: _receiver

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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 
開發者ID:sdn-ixp,項目名稱:iSDX,代碼行數:18,代碼來源:client.py

示例8: main

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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() 
開發者ID:sdn-ixp,項目名稱:iSDX,代碼行數:24,代碼來源:arproxy.py

示例9: test_distro_detection

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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'
        _() 
開發者ID:mbusb,項目名稱:multibootusb,代碼行數:23,代碼來源:test-distro.py

示例10: plot_examples

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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)) 
開發者ID:priba,項目名稱:nmp_qc,代碼行數:27,代碼來源:demo_letter_duvenaud.py

示例11: cd

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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())

    # 判斷輸入的命令並執行對應的函數 
開發者ID:11ze,項目名稱:The-chat-room,代碼行數:25,代碼來源:server.py

示例12: run_apidoc

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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) 
開發者ID:NLeSC,項目名稱:python-template,代碼行數:27,代碼來源:conf.py

示例13: has_system_site_packages

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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) 
開發者ID:edmundmok,項目名稱:mealpy,代碼行數:21,代碼來源:venv_update.py

示例14: test_write_csv

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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) 
開發者ID:JosephLai241,項目名稱:URS,代碼行數:21,代碼來源:test_Export.py

示例15: test_rmtree_test

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import path [as 別名]
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)) 
開發者ID:calmjs,項目名稱:calmjs,代碼行數:19,代碼來源:test_testing.py


注:本文中的sys.path方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。