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
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.
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
…
Related
I am brand new to working with python so this question might be basic. I am attempting to import five helper files into a primary script, the directory setup is as follows and both the script I'm calling from and the helper scripts are located within src here in this path-
/Users/myusername/Desktop/abd-datatable/src
I am currently importing as-
import helper1 as fdh
import helper2 as hdh
..
import helper5 as constants
The error I see is
File "/Users/myusername/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/22.77756/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
ModuleNotFoundError: No module named 'src'
I have also attempted the following for which the import was still unsuccessful:
import src.helper1 as fdh
..
import src.helper5 as constants
and
from src import src.helper1 as fdh
...
from src import helper5 as constants
and tried adding the following to the head of the script-
import sys
import os
module_path = os.path.abspath(os.getcwd())
if module_path not in sys.path:
sys.path.append(module_path)
Would be very grateful for any pointers on how to debug this!
Seems likely that it's a path issue.
In your case, if you want to import from src, you would need to add Users/myusername/Desktop/abd-datatable to the path.
os.getcwd() is getting the path you invoke the script from, so it would only work if you are invoking the script from Users/myusername/Desktop/abd-datatable.
I have two scripts in the same folder:
5057_Basic_Flow_Acquire.xyzpy
5006_Basic_Flow_Execute.xyzpy
I need to call function run() from 5057_Basic_Flow_Acquire file in the 5006_Basic_Flow_Execute file.
I tried two approaches:
1.
import time
import os
import sys
import types
dir_path = os.path.dirname(os.path.realpath(__file__))
#os.chdir(str(dir_path))
sys.path.append(str(dir_path))
sensor = __import__('5057_Basic_Flow_Acquire')
import time
import os
import sys
import types
import importlib
import importlib.util
dir_path = os.path.dirname(os.path.realpath(__file__))
spec = importlib.util.spec_from_file_location('run', dir_path+'\\5057_Basic_Flow_Acquire')
module = importlib.util.module_from_spec(spec)
Pycharm is reporting this type of errors:
case:
ModuleNotFoundError: No module named '5057_Basic_Flow_Acquire'
case
AttributeError: 'NoneType' object has no attribute 'loader'
So in both cases module was not found.
Does someone have any suggestion?
You should rename your files to something like :
5057_Basic_Flow_Acquire_xyz.py
5006_Basic_Flow_Execute_xyz.py
so that they are recognized as modules and can be imported.
Then, in your 5057_Basic_Flow_Acquire_xyz module, you can import the run function with the following line :
from 5006_Basic_Flow_Execute_xyz import run
Both files are in the same directory, so you should be able to import without changing your PATH environment variable as the current directory is automatically added at the top of the list.
I have a python script in PythonCode folder. I want that I should get the path excluding the PythonCode from it when using os.path.dirname(__file__), currently when I am using os.path.dirname(__file__) it is returning this:-
C:\Users\xyz\Documents\ABC\Python Code
but I need this path:-
C:\Users\xyz\Documents\ABC\
import os
dirname = os.path.dirname(__file__)
print (dirname)
You can wrap dirname once again to go up a directory
dirname=os.path.dirname(os.path.dirname(path))
Just call os.path.dirname() again on what you have:
import os
dirname = r"C:\Users\xyz\Documents\ABC\Python Code"
wanted = os.path.dirname(dirname)
print(wanted) # -> C:\Users\xyz\Documents\ABC
This has been already answered here.
You can do something like this,
import os
print(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))
The other answers use os.path, but you could also use the standard library pathlib module (https://docs.python.org/3/library/pathlib.html), which some people prefer because of its more intuitive object-oriented interface:
from pathlib import Path
wanted = Path(__file__).parent.parent
wanted_as_string = str(wanted)
My script is trying to read my utils from a different folder. I keep getting Import Error. PFB my script :
import sys
import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname+"/../../dags/golden/")
dname = os.path.dirname(abspath)
sys.path.append(dname)
import utils
semantics_config = utils.get_config()
And my folder structure is as follows :
/home/scripts/golden/script.py
/home/dags/golden/utils.py
Output is :
Traceback (most recent call last):
File "check.py", line 22, in
import utils
ImportError: No module named utils
Any pointers will be greatly helpful!
Try this
import sys
import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname+"/../../dags/golden/")
dname = os.getcwd()
sys.path.append(dname)
import utils
semantics_config = utils.get_config()
You are again assigning "dname" as old path.
So use os.getcwd()
or
import sys
import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
sys.path.append(dname+"/../../dags/golden/")
import utils
semantics_config = utils.get_config()
You made a mistake in your script.
os.chdir(dname+"/../../dags/golden/"), only changes your current working directory, but not change the value of variable "abspath"
So the value of "dname" keep the same before and after your "os.chdir"
just do sys.path.append(dname+"/../../dags/golden/"), you will get what you want.
BTW, python is very easy to locating the problem and learn. Maybe, You just need to add a print before you using a variable. And, don't forge to remove those print before you release your scripts.
I need to reload all the python modules within a specified directory.
I've tried something like this:
import sys, os
import_folder = "C:\\myFolder"
sys.path.insert( 0 , import_folder )
for dir in os.listdir(import_folder):
name = os.path.splitext(dir)[0]
ext = os.path.splitext(dir)[1]
if ext == ".py":
import( eval(name) )
reload( eval(name) )
Anyone know how to do this correctly?
import os # we use os.path.join, os.path.basename
import sys # we use sys.path
import glob # we use glob.glob
import importlib # we use importlib.import_module
import_folder = 'C:\\myFolder'
sys.path.append(import_folder) # this tells python to look in `import_folder` for imports
for src_file in glob.glob(os.path.join(import_folder, '*.py')):
name = os.path.basename(src_file)[:-3]
importlib.import_module(name)
reload(sys.modules[name])
importlib.import_module(name)
There is the code. Now to the semantics of the whole thing: using importlib makes this a little bit more normal, but it still promotes some bugs. You can see that this breaks for source files in a subdirectory. What you should probably do is: import the package, (import the whole folder), and use the . operator like so:
import sys # we use sys.path
sys.path.append('C:\\')
import myFolder
...
myFolder.func1(foo)
myFolder.val
bar = myFolder.Class1()
Perhaps you should take a look at the documentation for modules, but don't forget to update the path to include the parent of the folder you want to import.