Reputation: 197
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()
?
Upvotes: 1
Views: 5105
Reputation: 432
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
Upvotes: 0
Reputation: 15058
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, anda.insert(len(a), x)
is equivalent toa.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')
Upvotes: 1
Reputation:
You could insert it rather than append if you prefer:
import sys
sys.path.insert(0, "/home/btilley/brads_py_modules")
import your_modules
Upvotes: 0
Reputation: 2816
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')
Upvotes: 0