[英]How to run a Python file not in directory from another Python file?
Let's say I have a file foo.py, and within the file I want to execute a file bar.py. 假设我有一个文件foo.py,并且在文件中我想执行一个文件bar.py. But, bar.py isn't in the same directory as foo.py, it's in a subdirectory call baz.
但是,bar.py与foo.py不在同一目录中,它位于子目录调用baz中。 Will
execfile
work? execfile
工作吗? What about os.system
? 那么
os.system
呢?
Just add an empty __init__.py
file to signal baz
is a module and, from foo.py
do: 只需添加一个空的
__init__.py
文件来表示baz
是一个模块,并且从foo.py
执行:
from baz import bar
Unless, of course, you have a good reason not to make baz
into a module (and use execfile). 当然,除非你有充分的理由不让
baz
进入模块(并使用execfile)。
import sys,通过在运行时附加路径来更改“sys.path”,然后导入将有用的模块
Question implies that you want to run these as scripts, so yes: you could use execfile in 2.X or subprocess (call the interpreter and pass the script as an argument). 问题意味着您希望将这些作为脚本运行,所以是的:您可以在2.X或子进程中使用execfile(调用解释器并将脚本作为参数传递)。 You just need to provide absolute paths to the files.
您只需要提供文件的绝对路径。
# Python 2.X only!
execfile ('c:/python/scripts/foo/baz/baz.py')
Doing it that literally is brittle, of course. 当然,这样做实际上是脆弱的。 If baz is always a subirectory of foo you could derive it from foo's file :
如果baz总是foo的子目录,你可以从foo的文件中导出它:
baz_dir = os.path.join(os.path.dirname(__file__), "baz")
baz_file = os.path.join(baz_dir, "baz.py")
execfile(baz_file)
If both files are in locations that can be seen by your python -- ie, the folders are in sys.path or have been added to the search path using site you can import baz from foo and call it's functions directly. 如果两个文件都在python可以看到的位置 - 即,文件夹在sys.path中或者已经使用site添加到搜索路径中,则可以从foo导入baz并直接调用它的函数。 If you need to actually act on information from baz, instead of just triggering an action, this is a better way to go.
如果您需要实际处理来自baz的信息,而不仅仅是触发一个动作,这是一个更好的方法。 As long as there is an init .py in each folder You could just do
只要每个文件夹中都有一个init .py就可以了
import baz
baz.do_a_function_defined_in_baz()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.