3

I want to change os.path in os.py, but it failed. path is different in different platform.

os.py

import ntpath as path
sys.modules['os.path'] = path
from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep, devnull)

It turns out that

    from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
devnull)
ImportError: No module named path
11
  • @zetysz sorry, could you tell more? I don't understand. Commented Dec 9, 2015 at 8:17
  • os.path is not a module... Commented Dec 9, 2015 at 8:23
  • I think that zetysz is suggesting that you do: vars(os.path).update(vars(ntpath)) -- Which should replace os.path methods with their nt counterparts (or do nothing if you're on windows. . .) Commented Dec 9, 2015 at 8:25
  • Cannot reproduce your problem. Did you name your program os.py? Commented Dec 9, 2015 at 8:28
  • @zetysz, just saw it, im retrieving info, thanks for it mate :) Commented Dec 9, 2015 at 8:28

2 Answers 2

2

Your approach should work. Rename the subdirectory os in your current directory to my_os. Python finds your os directory first and tries to import from there.

Adding this line:

__future__ import absolute_import

to the beginning of the os.py avoids this problem by using absolute imports.

Sign up to request clarification or add additional context in comments.

1 Comment

I add from __future__ import absolute_import to the beginning. it works. Interpreter will find os.path in sys.modules but current file.
1

did you try with "__import__" function ?

import mtpath as path
os_path = __import__(path, globals(), locals(), ['curdir', 'pardir', 'sep', 'pathsep', 'defpath', 'extsep', 'altsep', 'devnull']

Then, you can use 'curdir' as :

os_path.curdir

Well, you can also asign it to 'curdir' name as in the documentation :

curdir = os_path.curdir
pardir = os_path.curdir
…

2 Comments

but we can not use it in other files。
I want to replace os.py modules. The new os.py can be portable. So os.path must be replaced.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.