Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:execfile来自其他文件';工作目录是什么?_Python_Working Directory_Execfile - Fatal编程技术网

Python:execfile来自其他文件';工作目录是什么?

Python:execfile来自其他文件';工作目录是什么?,python,working-directory,execfile,Python,Working Directory,Execfile,我有一些代码加载默认配置文件,然后允许用户提供自己的Python文件作为附加的补充配置或默认设置的覆盖: # foo.py def load(cfg_path=None): # load default configuration exec(default_config) # load user-specific configuration if cfg_path: execfile(cfg_path) 但是有一个问题:execfile()执

我有一些代码加载默认配置文件,然后允许用户提供自己的Python文件作为附加的补充配置或默认设置的覆盖:

# foo.py

def load(cfg_path=None):
    # load default configuration
    exec(default_config)

    # load user-specific configuration
    if cfg_path:
        execfile(cfg_path)
但是有一个问题:
execfile()
执行由
cfg\u path
指定的文件中的指令,就像它在
foo.py
的工作目录中一样,而不是它自己的工作目录中。因此,
import
指令可能会失败,如果
cfg\u路径
文件执行,例如,
来自m import x
,其中
m
是与
cfg\u路径
位于同一目录中的模块

如何从其参数的工作目录中执行
execfile()
,或者以其他方式实现等效结果?另外,有人告诉我,Python3中不推荐使用
execfile
,我应该使用
exec
,所以如果有更好的方法,我会洗耳恭听

注意:我不认为仅仅改变工作目录的解决方案是正确的。据我所知,这不会将这些模块放在解释器的模块查找路径上。

允许您根据需要更改工作目录(您可以使用
os.path.dirname
提取
cfg_path
的工作目录);如果要在执行完
cfg\u path
后还原当前目录,请确保首先获取当前目录

Python3确实删除了
execfile
(支持读取文件,
compile
内容,然后
exec
内容的顺序),但是如果您目前使用Python2.6进行编码,则不必担心这一点,因为源代码到源代码的转换可以顺利无缝地处理所有这些问题

编辑:OP在评论中说,
execfile
启动一个单独的进程,不尊重当前工作目录。这是错误的,下面是一个例子,表明它是:

import os

def makeascript(where):
  f = open(where, 'w')
  f.write('import os\nprint "Dir in file:", os.getcwd()\n')
  f.close()

def main():
  where = '/tmp/bah.py'
  makeascript(where)
  execfile(where)
  os.chdir('/tmp')
  execfile(where)

if __name__ == '__main__':
  main()
在我的机器上运行此操作会产生如下输出:

Dir in file: /Users/aleax/stko
Dir in file: /private/tmp
清楚地显示
execfile
是否继续使用在执行
execfile
时设置的工作目录。(如果执行的文件更改了工作目录,这将在
execfile
返回后反映出来——正是因为所有都是在同一个过程中发生的!)


因此,OP仍然观察到的任何问题都与当前工作目录无关(如果不查看代码和观察到的问题的确切细节,很难诊断它们实际上可能是什么;-)。

感谢您的回答。不幸的是,这似乎对我不起作用
execfile()
似乎正在启动一个全新的进程,它有自己的工作目录,这与我从中启动的目录不同。不,@Kyle,
execfile
不启动单独的进程,并且它尊重当前的工作目录。编辑我的答案,展示一个证明你错了的简单例子。