如何编写Python模块/软件包?

发布于 2021-02-02 23:08:56

我一直在为工作中的简单任务制作Python脚本,从来没有真正打扰过将它们打包供其他人使用。现在,我被分配为REST API制作Python包装器。我对如何开始一无所知,我需要帮助。

我有的:

(只想尽可能地具体一点)我已经准备好virtualenv,它也位于github中,还存在用于python的.gitignore文件,以及用于与REST API交互的请求库。而已。

这是当前目录树

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

27 directories, 280 files

我什至不知道将.py文件放在哪里。

我想做的是:

使用“ pip install ...”制作可安装的python模块

如果可能的话,我需要一个逐步的编写Python模块的常规过程。

关注者
0
被浏览
89
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

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

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

    def helloworld():
       print "hello"
    

    然后,你可以导入hello

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

    要对许多.py文件进行分组,请将它们放在文件夹中。带有的任何文件夹__init__.py都被python视为模块,你可以将其称为包

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

    |
    你可以按照通常的方式在模块上使用import语句。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看