Why open() in python not use windows enviroment variables like a import -


i have file on desktop, full path:

c:\users\evgeny\desktop\f.py

but python ran from:

c:\users\evgeny

the problem is, can't exec(open('f.py').read())

i include first path enviroment variables, doesn't work. example, when

import f works okay.

enter image description here

can possible run open('f.py') directory not using full path file?

open() tool open any file on filesystem. not tool find python modules.

python's import machinery complex (it can extended, adjusting how modules found or loaded) , out of box supports cached bytecode files different extensions (.pyc, .pyd, in __bytecache__ directory or not), loading .zip files, , loading native extensions, series of configurable directories listed on sys.path. machinery there allow override modules different versions, putting them in different location on search path.

the vast majority of use-cases open() function, however, not need machinery, want open cat pictures desktop, , not have worry cat.py module in different directory.

you can re-use module resolution behaviour of import machinery using the importlib.util.find_spec() module:

from importlib.util import find_spec  module_spec = find_spec('f') if module_spec not none:     open(module_spec.origin) module_source:         exec(module_source.read()) 

this require desktop folder on sys.path module search path.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -