Reputation: 62624
Assuming my directory structure is:
C:\Scripts\myscript.py
C:\Scripts\customjson\json.py
The myscript.py python script has at the top:
sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), 'customjson'))
import json
The thing is, I have a "customjson" folder that contains a json.py that I want to use instead of the default json package that Python 2.7 comes with. How do I make it so that the script uses "customjson" instead of the standard json?
Upvotes: 2
Views: 364
Reputation: 104712
I say: Make your customjson
folder a package.
It's easy:
__init__.py
in your customjson folder. The file can be empty if you don't want anything special defined at the package level.import
statement to refer to the module within the package (i.e. import customjson.json
).import
statement to include as as
clause (import customjson.json as json
). If you're using from ... import ...
syntax, this is unnecessary. While using an as
clause may be easier than rewriting your accesses, it may confusing any other programmer who reads your code and expects it to be using the standard json module.Given the folder layout you describe in the question, you won't need to mess around with the module search path at all if you go this route, since the running script's current folder is always included in the path and that's where the customjson package is located.
Upvotes: 0
Reputation: 6777
You could use something like this:
import sys
_orig_path = sys.path
sys.path = ["C:\Scripts\customjson"]
import json
sys.path = _orig_path
But, of course, that code wouldn't be portable. To make it portable, you could use:
import sys, os
_orig_path = sys.path
sys.path = [
os.path.abspath(os.path.join(os.path.dirname(__file__), "customjson")),
]
import json
sys.path = _orig_path
Or, you could rename json.py
to, for example, json2.py
. And then import it:
import json2
or, if you absolutely need it to be named json
:
import json2 as json
..yeah, the second one looks better, doesn't it?
Upvotes: 0
Reputation: 10541
Try to insert your customjson directory first in sys.path
:
sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), 'customjson'))
import json
Upvotes: 2