Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to temporarily modify sys.path in Python?

In one of my testing scripts in Python I use this pattern several times:

sys.path.insert(0, "somedir") mod =  __import__(mymod) sys.path.pop(0) 

Is there a more concise way to temporarily modify the search path?

like image 273
planetp Avatar asked Jun 20 '13 10:06

planetp


People also ask

How do I temporarily add to Python path?

Just use sys. path. remove(self. path) instead of sys.

Is SYS path append permanent?

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

What is SYS path append (' ')?

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.


1 Answers

You could use a simple context manager:

import sys  class add_path():     def __init__(self, path):         self.path = path      def __enter__(self):         sys.path.insert(0, self.path)      def __exit__(self, exc_type, exc_value, traceback):         try:             sys.path.remove(self.path)         except ValueError:             pass 

Then to import a module you can do:

with add_path('/path/to/dir'):     mod = __import__('mymodule') 

On exit from the body of the with statement sys.path will be restored to the original state. If you only use the module within that block you might also want to delete its reference from sys.modules:

del sys.modules['mymodule'] 
like image 97
Eugene Yarmash Avatar answered Sep 22 '22 04:09

Eugene Yarmash