2

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?

Rostyslav Dzinko
  • 39,424
  • 5
  • 49
  • 62
Rolando
  • 58,640
  • 98
  • 266
  • 407
  • 3
    Why do you insist on calling your version 'json' too? – jordanm Aug 10 '12 at 19:49
  • 1
    Your module DEFINITELY should have a different name, for God's sake! – heltonbiker Aug 10 '12 at 19:49
  • I am trying to use a custom modification to an older version of the json module. If there is an alternative way I should call it, let me know. What changes should I make such that it is a different name? – Rolando Aug 10 '12 at 19:50

3 Answers3

2

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
Fedor Gogolev
  • 10,391
  • 4
  • 30
  • 36
0

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?

redShadow
  • 6,687
  • 2
  • 31
  • 34
0

I say: Make your customjson folder a package.

It's easy:

  1. Create a file named __init__.py in your customjson folder. The file can be empty if you don't want anything special defined at the package level.
  2. Change your import statement to refer to the module within the package (i.e. import customjson.json).
  3. Change your references to the module to use the full path (customjson.json.whatever), or instead further change your 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.

Blckknght
  • 100,903
  • 11
  • 120
  • 169