I ' mtryingtoimportautilitiesfilebutrunningintoaweirderroronlywhenirunthecodethroughascript。
When I run test.py
location :/home/amour av/python/proj/test.py
代码:
import os
OS.chdir (r '/home/amour av/python/' ) )。
printOS.listdir(OS.getcwd ) )
print os.getcwd (
来自用户导入*
The output is:
['UTILS_local.py ',' UTILS.py ',' proj ',' UTILS.pyc']
/home/amourav/Python
跟踪后台(mostrecentcalllast ) :
File 'UNET_2D_AUG17.py ',line 11,in
来自用户导入*
butwhenirunthecodethroughthebashterminal,it seems to work fine
bash-4.1$ python
import os
OS.chdir (r '/home/amour av/python/' ) )。
printOS.listdir(OS.getcwd ) )
['UTILS_local.py ',' UTILS.py ',' proj ',' UTILS.pyc']
来自用户导入*
blah blah-everythingisfine-blah blah
I ' mrunningpython 2.7.10 onalinuxmachine
Your project looks like this:
If you like to import UTILS.py,you can choose:
)1) add the path to sys.path in test.py
import os,sys
sys.path.append(OS.path.join ) OS.path.Dirname(__file_,'.') )
# nowyoumaygetaproblemwithwhatiwrotebelow。
导入实用程序
((2) createapackage ) ) importsonly ) )。
Now,youcanwritethisintest.pyifyouimportpython.proj.test 3360
from . import UTILS
WRONG ANSWER
ihadthiserrorseveraltimes.ithink,I remember。
Fix: do not run test.py,run ./test.py。
If you have a look at sys.path,youcanseethatthereisanemptystringidewhichisthepathofthefileexecuted。
test.py adds '' to sys.path
./test.py adds '.' to sys.path
Imports can only be performed from '.',I think。