pyqt4 - importing a python function from a file in other directory which depends on another file -


this directory structure

-directory1   |-currentlywritingcode -directory2   |-__init__.py   |-helper.py   |-view.ui 

the helper.py ui pyqt4 framework. needs view.ui file . has following code load ui data

viewbase, viewform = uic.loaduitype("view.ui") 

now in directory1 in writing code did this

import directory2.helper 

when run code in currentlywritingcode throwing error

filenotfounderror: [errno 2] no such file or directory: 'view.ui' 

what now?

using python3.5 anaconda on centos 7

use os.path.join(os.path.dirname(os.path.realpath(__file__)),'view.ui') in place of view.ui. ensure correctly reference folder python file lives in, regardless of code imports it.

note: make sure have import os other imports.

how work?

__file__ attribute of module importing. contains path module file. see this answer. however, path not absolute path. os.path.realpath returns absolute path (it follows symlinks if there any). @ point have full path module, take path directory (os.path.dirname) , join original filename (which assumed relative original module , should in aforementioned directory). os.path.join ensures correct \ or / used when constructing file path code works on platform.


Comments

Popular posts from this blog

SVG stroke-linecap doesn't work for circles in Firefox? -

routes - Laravel 4 Wildcard Routing to Different Controllers -

cross browser - XSLT namespace-alias Not Working in Firefox or Chrome -