Convert your Python scripts into command line programs
I've written, used, and seen a lot of random scripts throughout my career. Some people need semi-automated tasks, so they were born. After a while, they get bigger and bigger. They may change hands many times during a lifetime. I often wish these scripts provided more of a command-line tool-like feel. But how hard is it to go from one-off scripts to the right tools to really improve the level of quality? Turns out this isn't that hard in Python.
Building a skeleton script
In this article, I will start with a small piece of Python code. I will apply this into the scaffold
module and extend it using the click
library to accept command line arguments.
#!/usr/bin/python from glob import glob from os.path import join, basename from shutil import move from datetime import datetime from os import link, unlink LATEST = 'latest.txt' ARCHIVE = '/Users/mark/archive' INCOMING = '/Users/mark/incoming' TPATTERN = '%Y-%m-%d' def transmogrify_filename(fname): bname = basename(fname) ts = datetime.now().strftime(TPATTERN) return '-'.join([ts, bname]) def set_current_latest(file): latest = join(ARCHIVE, LATEST) try: unlink(latest) except: pass link(file, latest) def rotate_file(source): target = join(ARCHIVE, transmogrify_filename(source)) move(source, target) set_current_latest(target) def rotoscope(): file_no = 0 folder = join(INCOMING, '*.txt') print(f'Looking in {INCOMING}') for file in glob(folder): rotate_file(file) print(f'Rotated: {file}') file_no = file_no + 1 print(f'Total files rotated: {file_no}') if __name__ == '__main__': print('This is rotoscope 0.4.1. Bleep, bloop.') rotoscope()
For all the code examples not shown here, you can find specific versions in https://www.php.cn/link/575afbdca5a101e3088b2b6554398b0c code. Each commit in this repository describes some meaningful step in the process of this article.
This snippet does several things:- Checks whether there is a text file in the specified path
If exists, create a new filename with the current timestamp and move it to
ARCHIVE Delete the current
ARCHIVE/latest.txt Link and create a new link to the file you just addedAs an example, it's simple but it will give you an understanding of the process.
scaffold
, click and
tox
Python library.
$ python3 -m pip install scaffold click tox
rotoscope project is located, and then execute the following command:
$ putup rotoscope -p rotoscope --force --no-skeleton -n rotoscope -d 'Move some files around.' -l GLWT -u http://codeberg.org/ofosos/rotoscope --save-config --pre-commit --markdown
Pyscaffold will rewrite my
README.md, so restoring it from Git: $ git checkout README.md
Pyscaffold explains how to set up a complete example project in the documentation , I won’t introduce it here, you can explore it later. In addition, Pyscaffold can also provide you with continuous integration (CI) templates in your project:
- 打包: 你的项目现在启用了 PyPi,所以你可以将其上传到一个仓库并从那里安装它。
- 文档: 你的项目现在有了一个完整的文档文件夹层次结构,它基于 Sphinx,包括一个readthedocs.org 构建器。
- 测试: 你的项目现在可以与 tox 一起使用,测试文件夹包含运行基于 pytest 的测试所需的所有样板文件。
- 依赖管理: 打包和测试基础结构都需要一种管理依赖关系的方法。
setup.cfg
文件解决了这个问题,它包含所有依赖项。 - 预提交钩子: 包括 Python 源代码格式工具 black 和 Python 风格检查器 flake8。
查看测试文件夹并在项目目录中运行 tox
命令,它会立即输出一个错误:打包基础设施无法找到相关库。
现在创建一个 Git
标记(例如 v0.2
),此工具会将其识别为可安装版本。在提交更改之前,浏览一下自动生成的 setup.cfg
并根据需要编辑它。对于此示例,你可以修改 LICENSE
和项目描述,将这些更改添加到 Git 的暂存区,我必须禁用预提交钩子,然后提交它们。否则,我会遇到错误,因为 Python 风格检查器 flake8 会抱怨糟糕的格式。
$ PRE_COMMIT_ALLOW_NO_CONFIG=1 git commit
如果这个脚本有一个入口点,用户可以从命令行调用,那就更好了。现在,你只能通过找 .py
文件并手动执行它来运行。幸运的是,Python 的打包基础设施有一个很好的“罐装”方式,可以轻松地进行配置更改。将以下内容添加到 setup.cfg
的 options.entry_points
部分:
console_scripts = roto = rotoscope.rotoscope:rotoscope
这个更改会创建一个名为 roto
的 shell 命令,你可以使用它来调用 rotoscope 脚本,使用 pip
安装 rotoscope 后,可以使用 roto
命令。
就是这样,你可以从 Pyscaffold 免费获得所有打包、测试和文档设置。你还获得了一个预提交钩子来保证(大部分情况下)你按照设定规则提交。
CLI 工具化
现在,一些值会硬编码到脚本中,它们作为命令 参数 会更方便。例如,将 INCOMING
常量作为命令行参数会更好。
首先,导入 click 库,使用 Click 提供的命令装饰器对 rotoscope()
方法进行装饰,并添加一个 Click 传递给 rotoscope
函数的参数。Click 提供了一组验证器,因此要向参数添加一个路径验证器。Click 还方便地使用函数的内嵌字符串作为命令行文档的一部分。所以你最终会得到以下方法签名:
@click.command() @click.argument('incoming', type=click.Path(exists=True)) def rotoscope(incoming): """ Rotoscope 0.4 - Bleep, blooop. Simple sample that move files. """
主函数会调用 rotoscope()
,它现在是一个 Click 命令,不需要传递任何参数。
选项也可以使用 环境变量 自动填充。例如,将 ARCHIVE
常量改为一个选项:
@click.option('archive', '--archive', default='/Users/mark/archive', envvar='ROTO_ARCHIVE', type=click.Path())
使用相同的路径验证器。这一次,让 Click 填充环境变量,如果环境变量没有提供任何内容,则默认为旧常量的值。
Click 可以做更多的事情,它有彩色的控制台输出、提示和子命令,可以让你构建复杂的 CLI 工具。浏览 Click 文档会发现它的更多功能。
现在添加一些测试。
测试
Click 对使用 CLI 运行器 运行端到端测试 提供了一些建议。你可以用它来实现一个完整的测试(在 示例项目 中,测试在 tests
文件夹中。)
测试位于测试类的一个方法中。大多数约定与我在其他 Python 项目中使用的非常接近,但有一些细节,因为 rotoscope 使用 click
。在 test
方法中,我创建了一个 CliRunner
。测试使用它在一个隔离的文件系统中运行此命令。然后测试在隔离的文件系统中创建 incoming
和 archive
目录和一个虚拟的 incoming/test.txt
文件,然后它调用 CliRunner,就像你调用命令行应用程序一样。运行完成后,测试会检查隔离的文件系统,并验证 incoming
为空,并且 archive
包含两个文件(最新链接和存档文件)。
from os import listdir, mkdir from click.testing import CliRunner from rotoscope.rotoscope import rotoscope class TestRotoscope: def test_roto_good(self, tmp_path): runner = CliRunner() with runner.isolated_filesystem(temp_dir=tmp_path) as td: mkdir("incoming") mkdir("archive") with open("incoming/test.txt", "w") as f: f.write("hello") result = runner.invoke(rotoscope, ["incoming", "--archive", "archive"]) assert result.exit_code == 0 print(td) incoming_f = listdir("incoming") archive_f = listdir("archive") assert len(incoming_f) == 0 assert len(archive_f) == 2
要在控制台上执行这些测试,在项目的根目录中运行 tox
。
在执行测试期间,我在代码中发现了一个错误。当我进行 Click 转换时,rotoscope
只是取消了最新文件的链接,无论它是否存在。测试从一个新的文件系统(不是我的主文件夹)开始,很快就失败了。我可以通过在一个很好的隔离和自动化测试环境中运行来防止这种错误。这将避免很多“它在我的机器上正常工作”的问题。
搭建骨架脚本和模块
本文到此结束,我们可以使用 scaffold
和 click
完成一些高级操作。有很多方法可以升级一个普通的 Python 脚本,甚至可以将你的简单实用程序变成成熟的 CLI 工具。
The above is the detailed content of Convert your Python scripts into command line programs. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
