Table of Contents
Building a skeleton script
​scaffold​
CLI 工具化
测试
搭建骨架脚本和模块
Home Backend Development Python Tutorial Convert your Python scripts into command line programs

Convert your Python scripts into command line programs

Apr 13, 2023 pm 01:46 PM
python

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()
Copy after login

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 added
  • As an example, it's simple but it will give you an understanding of the process.
Create an application using Pyscaffold

First, you need to install ​

​scaffold​

​​, ​

​click​​​ and ​​tox​​​ ​​Python library​​.

$ python3 -m pip install scaffold click tox
Copy after login
After installing ​​scaffold​

​​, switch to the directory where the example ​

​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
Copy after login
Pyscaffold will rewrite my ​​README.md​

​, so restoring it from Git:

$ git checkout README.md
Copy after login
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
Copy after login

如果这个脚本有一个入口点,用户可以从命令行调用,那就更好了。现在,你只能通过找 ​​.py​​​ 文件并手动执行它来运行。幸运的是,Python 的打包基础设施有一个很好的“罐装”方式,可以轻松地进行配置更改。将以下内容添加到 ​​setup.cfg​​​ 的 ​​options.entry_points​​ 部分:

console_scripts =

roto = rotoscope.rotoscope:rotoscope
Copy after login

这个更改会创建一个名为 ​​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.

"""
Copy after login

主函数会调用 ​​rotoscope()​​,它现在是一个 Click 命令,不需要传递任何参数。

选项也可以使用 ​​环境变量​​​ 自动填充。例如,将 ​​ARCHIVE​​ 常量改为一个选项:

@click.option('archive', '--archive', default='/Users/mark/archive', envvar='ROTO_ARCHIVE', type=click.Path())
Copy after login

使用相同的路径验证器。这一次,让 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
Copy after login

要在控制台上执行这些测试,在项目的根目录中运行 ​​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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

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.

See all articles