如何在python中使用通用代码? [英] How can I use common code in python?

查看:95
本文介绍了如何在python中使用通用代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在维护自己的两个应用程序.它们都共享一些共同的方面,因此,它们共享一些代码.到目前为止,我只是将模块从一个项目复制到了另一个项目,但是现在这已成为维护问题.我希望将通用代码放在两个项目都可以导入的两个项目之外的一个地方.然后,对通用代码的任何更改都将反映在两个项目中.

I'm currently maintaining two of my own applications. They both share some common aspects, and as a result, share some code. So far, I've just copied the modules from one project to the other, but now it's becoming a maintenance issue. I'd rather have the common code in one place, outside of both of the projects, which they can both import. Then, any changes to the common code would be reflected in both project.

我的问题是:我该怎么做?我是否可以使用此代码创建一个库?如果是这样,从属项目如何使用该库?我认为我在这里遇到的一件事是通用代码对其他人并没有真正的用处,或者至少我不想使其成为其他人可以使用的受支持模块.

My question is: how can I do this? Do I create a library out of this code? If so, how do the dependent projects use the library? I think one thing I struggle with here is that the common code isn't really useful to anyone else, or at least, I don't want to make it a supported modules that other people can use.

如果我的问题不清楚,请告诉我.

If my question isn't clear, please let me know.

推荐答案

您无需执行任何特殊操作,Python只需查找您的模块即可.这意味着您必须将通用模块放入PYTHONPATH中,或者将其位置添加到sys.path中. 参见此内容.

There is nothing special you have to do, Python just needs to find your module. This means that you have to put your common module into your PYTHONPATH, or you add their location to sys.path. See this.

说你有

~/python/project1
~/python/project2
~/python/libs/stuff.py
~/python/libs/other.py

您可以在操作系统环境中设置PYTHONPATH='~/python/libs',也可以

You can either set PYTHONPATH='~/python/libs' in your os enviroment, or you can do

import sys, os
sys.path.append(os.path.expanduser('~/python/libs')) # or give the full path

之后,您可以在任何地方执行import stuff, other.

After that you can do import stuff, other anywhere.

您还可以打包您的东西,然后需要这样的布局:

You can also package your stuff, then you need a layout like this:

~/python/project1
~/python/project2
~/python/libs/mylibname/__init__.py
~/python/libs/mylibname/stuff.py
~/python/libs/mylibname/other.py

~/python/libs/mylibname/__init__.py必须存在,但它可以是一个空文件.它将mylibname转换为程序包.

~/python/libs/mylibname/__init__.py must exist, but it can be a empty file. It turns mylibname into a package.

将libs文件夹添加到上述路径后,即可执行from mylibname import stuff, other.

After adding the libs folder to your path as above, you can do from mylibname import stuff, other.

这篇关于如何在python中使用通用代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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