如何编写 Python 模块/包? [英] How to write a Python module/package?

查看:39
本文介绍了如何编写 Python 模块/包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为工作中的简单任务编写 Python 脚本,从不费心将它们打包以供其他人使用.现在我被指派为 REST API 制作一个 Python 包装器.我完全不知道如何开始,我需要帮助.

我有什么:

(只想尽可能具体)我有 virtualenv 准备好了,它也在 在 github 上,python 的 .gitignore 文件也在那里,此外,还有用于与 REST API 交互的 requests library.就是这样.

这是当前目录树

<预><代码>.├── 仓│ └──/平常的东西/├── 包括│ └──/平常的东西/├── 库│ └── python2.7│ └──/平常的东西/├── 本地│ └──/平常的东西/└── README.md27个目录,280个文件

我什至不知道把 .py 文件放在哪里,如果我做过的话.

我想做什么:

使用pip install ..."使python模块可安装

如果可能,我想要一个关于编写 Python 模块的一般分步过程.

解决方案

模块是包含 Python 定义和语句的文件.文件名是后缀.py

的模块名

创建 hello.py 然后编写以下函数作为其内容:

def helloworld():打印你好"

然后就可以导入hello:

<预><代码>>>>导入你好>>>hello.helloworld()'你好'>>>

要将多个 .py 文件组合在一起,将它们放在一个文件夹中.任何带有 __init__.py 的文件夹都被 python 视为模块,您可以将它们称为包

|-HelloModule|_ __init__.py|_ hellomodule.py

您可以按照通常的方式在模块上使用 import 语句.

有关详细信息,请参阅 6.4.包裹.

I've been making Python scripts for simple tasks at work and never really bothered packaging them for others to use. Now I have been assigned to make a Python wrapper for a REST API. I have absolutely no idea on how to start and I need help.

What I have:

(Just want to be specific as possible) I have the virtualenv ready, it's also up in github, the .gitignore file for python is there as well, plus, the requests library for interacting with the REST API. That's it.

Here's the current directory tree

.
├── bin
│   └── /the usual stuff/
├── include
│   └── /the usual stuff/
├── lib
│   └── python2.7
│       └── /the usual stuff/
├── local
│   └── /the usual stuff/
└── README.md

27 directories, 280 files

I don't even know where to put the .py files, if I ever make one.

What I wanted to do:

Make a python module install-able with "pip install ..."

If possible, I want a general step by step process on writing Python modules.

解决方案

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py

create hello.py then write the following function as its content:

def helloworld():
   print "hello"

Then you can import hello:

>>> import hello
>>> hello.helloworld()
'hello'
>>>

To group many .py files put them in a folder. Any folder with an __init__.py is considered a module by python and you can call them a package

|-HelloModule
  |_ __init__.py
  |_ hellomodule.py

You can go about with the import statement on your module the usual way.

For more information, see 6.4. Packages.

这篇关于如何编写 Python 模块/包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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