Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you modify sys.path in Google App Engine (Python)?

I've tried adding the following line to my handler script (main.py), but it doesn't seem to work:

sys.path.append('subdir')

subdir lives in the my root directory (i.e. the one containing app.yaml).

This doesn't seem to work, because when I try to import modules that live in subdir, my app explodes.

like image 264
allyourcode Avatar asked Mar 01 '10 06:03

allyourcode


People also ask

How does Python set SYS path?

sys. path is a built-in variable within the sys module. It contains a list of directories that the interpreter will search in for the required module. When a module(a module is a python file) is imported within a Python file, the interpreter first searches for the specified module among its built-in modules.

How is Python SYS path populated?

path is populated using the current working directory, followed by directories listed in your PYTHONPATH environment variable, followed by installation-dependent default paths, which are controlled by the site module.


1 Answers

1) Ensure you have a blank __init__.py file in subdir.

2) Use a full path; something like this:

import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), 'subdir'))

Edit: providing more info to answer questions asked in a comment.

As Nick Johnson demonstrates you can place those three lines of code in a file called fix_path.py. Then, in your main.py file, do this import fix_path before all other imports. Link to a tested application using this technique.

And, yes, the __init__.py file is required; per the documentation:

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

like image 83
mechanical_meat Avatar answered Nov 04 '22 14:11

mechanical_meat