简体   繁体   中英

In Python, sys.path.append('path/to/module') throws syntax error

I am trying to append the module path to my PYTHONPATH environment variable something like this

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

I am getting syntax error

Syntax error: word unexpected (expecting ")")

Can anyone help me with correct syntax for sys.path.append() ?

Both answers are correct.

append() by default adds your argument to the end of the list. It's throwing a syntax error as you are passing it 2 arguments and it is only accepting 1.

Judging by your syntax you want your path added to the front of the path so insert() is the method to use.

You can read more in the documentation on Data Structures

list.append(x)

Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.insert(i, x)

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to 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')

Why do you use import sys sys.path.append(0,"/path/to/module/abc.py");

Just try:

import sys

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

You could insert it rather than append if you prefer:

import sys

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

import your_modules

Here I have shown an example for help Appending module to path. paths is a list that has location of directories stored.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM