Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struggling to append a relative path to my sys.path

Tags:

So there are a lot of pretty similar questions but none of the answers seems to satisfy what I'm looking for.

Essentially I am running a python script using an absolute directory in the command line.
Within this file itself, I want to import a module/file,I currently use an absolute path to do this (sys.path.append(/....).
But I would like to use a relative path, relative to the script itself.
All I seem to be able to do is append a path relative to my present working directory.

How do I do this?

like image 864
user2564502 Avatar asked Jan 21 '14 13:01

user2564502


People also ask

What is SYS path append (' ')?

# printing all directories. sys.path. Output: APPENDING PATH- append() is a built-in function of sys module that can be used with path variable to add a specific path for interpreter to search.

How do you pass a relative path in Python?

First, you have to import the os module in Python so you can run operating system functionalities in your code. Then you create the variable absolute_path which fetches the current directory relative to the root folder. This is the full path to your working directory, in this case, ~/home/projects/example-project/ .

Is SYS path append permanent?

sys. path. append('/path/to/dir') does not permanently add the entry.


1 Answers

The two below alternate possibilities apply to both Python versions 2 and 3. Choose the way you prefer. All use cases are covered.

Example 1

main script:      /some/path/foo/foo.py module to import: /some/path/foo/bar/sub/dir/mymodule.py 

Add in foo.py

import sys, os sys.path.append(os.path.join(sys.path[0],'bar','sub','dir')) from mymodule import MyModule 

Example 2

main script:      /some/path/work/foo/foo.py module to import: /some/path/work/bar/mymodule.py 

Add in foo.py

import sys, os sys.path.append(os.path.join(os.path.dirname(sys.path[0]),'bar')) from mymodule import MyModule 

Explanations

  • sys.path[0] is /some/path/foo in both examples
  • os.path.join('a','b','c') is more portable than 'a/b/c'
  • os.path.dirname(mydir) is more portable than os.path.join(mydir,'..')

See also

Documentation about importing modules:

  • in Python 2
  • in Python 3
like image 60
oHo Avatar answered Oct 02 '22 13:10

oHo