[英]Run Python codes on subdirectories
如何在主文件夾的子目錄上運行python代碼(.py)?
最簡單的方法是什么?
我試過了:
os.chdir("path") #path = path to subdirectory
import abc #abc = module on subdirectory
錯誤:
ImportError: No module named abc
我相信您希望將abc
導入當前模塊,即使它們位於不同的文件夾中也是如此。 根據您的python,有不同的方法可以執行此操作:
Python2.x
import imp
abc = imp.load_source('abc', '/path/to/abc.py')
Python 3.4
from importlib.machinery import SourceFileLoader
abc = SourceFileLoader('abc', '/path/to/abc.py').load_module()
無論哪種情況, abc
都將照常導入。
>>> abc
<module 'abc' from '/path/to/abc.py'>
這比較干凈,因為它不涉及污染sys.path
。
看看這個
import sys
sys.path
sys.path.append('/path/to/the/example_file.py')
import example_file
好吧,就去做
import sys
sys.path
sys.path.append('/path/to/the/example_file1.py')
sys.path.append('/path/to/the/example_file2.py')
sys.path.append('/path/to/the/example_file3.py')
import example_file1
import example_file2
import example_file3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.