不使用.py扩展名从其他文件夹导入python
不使用.py扩展名从其他文件夹导入python 下面是我调用python脚本(distribute)的python脚本(feed_prg) 请注意,我的脚本位于不同的位置不使用.py扩展名从其他文件夹导入python,python,python-import,python-2.x,Python,Python Import,Python 2.x,不使用.py扩展名从其他文件夹导入python 下面是我调用python脚本(distribute)的python脚本(feed_prg) 请注意,我的脚本位于不同的位置 feed\u prg位于/opt/callscript位置 #!/usr/bin/env python import sys sys.dont_write_bytecode = True sys.path.append('/home/username') import distribute # Main method s
feed\u prg
位于/opt/callscript位置
#!/usr/bin/env python
import sys
sys.dont_write_bytecode = True
sys.path.append('/home/username')
import distribute
# Main method start execution
def main(argv):
something = 'some'
distribute.feed(something)
if __name__ == "__main__":
main(sys.argv[1:])
分发
位于/home/username
#!/usr/bin/env python
import sys
def feed(something):
print something
def main():
something= "some"
feed(something)
if __name__ == "__main__":
main()
我在执行./feed_prg时看到以下错误,并且仅当我的分发文件名为just distribute而不是distribute.py时
Traceback (most recent call last):
File "./feed_prg", line XX, in <module>
import distribute
ImportError: No module named distribute
回溯(最近一次呼叫最后一次):
文件“/feed_prg”,第XX行,在
进口分销
ImportError:没有名为distribute的模块
distribute还具有执行权限,如下所示
-rwxr-xr-x 1用户名3028 Dec 16 21:05分发
我怎样才能解决这个问题?任何输入都会有帮助
谢谢 直接使用
import
无法执行此操作。最好将文件重命名为.py
也就是说,根据您的Python版本,可以使用importlib
或imp
将模块加载到变量中
给定路径为
/distribute
(相对于python运行的位置)的以下文件:
Python 2
#python2import
从imp导入加载\u源
distribute=加载源(“distribute”,“distribute/distribute”)
打印(分发.a_变量)
用法:
$python2import
进口的!
5.
Python 3
#python3import
从importlib.machine导入SourceFileLoader
distribute=SourceFileLoader(“distribute”,“/distribute”).load_module()
打印(分发.a_变量)
用法:
$python3 python3导入
进口的!
5.
尽管我们使用的是较旧版本的Python(Python 2.6.6),但让我试试看
# distribute
print("Imported!")
a_var = 5