如何从另一个Python文件运行不在目录中的Python文件? [英] How to run a Python file not in directory from another Python file?

查看:174
本文介绍了如何从另一个Python文件运行不在目录中的Python文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个文件foo.py,并且在该文件内我想执行一个文件bar.py.但是,bar.py与foo.py不在同一个目录中,而是在一个名为baz的子目录中. execfile可以工作吗?那os.system呢?

Let's say I have a file foo.py, and within the file I want to execute a file bar.py. But, bar.py isn't in the same directory as foo.py, it's in a subdirectory call baz. Will execfile work? What about os.system?

推荐答案

只需添加一个空的__init__.py文件以指示baz是一个模块,然后从foo.py做:

Just add an empty __init__.py file to signal baz is a module and, from foo.py do:

from baz import bar

当然,除非您有充分的理由不将baz放入模块中(并使用execfile).

Unless, of course, you have a good reason not to make baz into a module (and use execfile).

这篇关于如何从另一个Python文件运行不在目录中的Python文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆