简体   繁体   中英

Python: Change the script's working directory to a different directory to read constants

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM