在Python中,sys.path.append('path / to / module')会引发语法错误

时间:2013-05-08 13:04:03

标签: python python-2.7

我正在尝试将模块路径附加到我的PYTHONPATH环境变量这样的

import sys
sys.path.append(0,"/path/to/module/abc.py")

我收到语法错误

Syntax error: word unexpected (expecting ")")

任何人都可以帮助我使用sys.path.append()的正确语法吗?

4 个答案:

答案 0 :(得分:1)

两个答案都是正确的。

默认情况下,

append()会将您的参数添加到列表的 end 。当你传递2个参数并且它只接受1时,它会抛出一个语法错误。

根据您的语法判断,您希望将路径添加到路径的,因此insert()是要使用的方法。

您可以在Data Structures

的文档中阅读更多内容
  

list.append(x)

     

将项目添加到列表的末尾;相当于   a [len(a):] = [x]。

     

list.insert(i, x)

     

在指定位置插入项目。首先   argument是要插入的元素的索引,所以   a.insert(0, x)位于列表的前面,a.insert(len(a), x)相当于a.append(x)

import sys
# Inserts at the front of your path
sys.path.insert(0, "/path/to/module/abc.py")
# Inserts at the end of your path
sys.path.append('/path/to/module/abc.py')

答案 1 :(得分:0)

为什么使用import sys sys.path.append(0,“/ path / to / module / abc.py”);

试试吧:

import sys

sys.path.append('/path/to/module/abc.py')

答案 2 :(得分:0)

如果您愿意,可以插入而不是追加:

import sys

sys.path.insert(0, "/home/btilley/brads_py_modules")

import your_modules

答案 3 :(得分:0)

这里我展示了一个帮助示例 将模块附加到路径。 paths是一个包含目录存储位置的列表。

def _get_modules(self, paths, toplevel=True):
    """Take files from the command line even if they don't end with .py."""
    modules = []
    for path in paths:
        path = os.path.abspath(path)
        if toplevel and path.endswith('.pyc'):
            sys.exit('.pyc files are not supported: {0}'.format(path))
        if os.path.isfile(path) and (path.endswith('.py') or toplevel):
            modules.append(path)                        
        elif os.path.isdir(path):                       
            subpaths = [
                os.path.join(path, filename)
                for filename in sorted(os.listdir(path))]           
            modules.extend(self._get_modules(subpaths, toplevel=False))
        elif toplevel:
            sys.exit('Error: %s could not be found.' % path)
    return modules