本文介绍了Scripts 目录是 Python 中的反模式吗?如果是这样,导入的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是在我构建的每个项目中创建脚本目录,因为它们对于放置不常用的可执行脚本很有用.在 Python 中,我总是将 __init__.py 放在我的脚本目录中,这样我就可以将脚本作为包运行(即 python -m scripts.some_scripts)并从中加载模块姐妹目录.基于 this 以及谷歌搜索,我开始得到感觉这是一种反模式.

I've always created scripts directories in every project I've built because they're useful for putting infrequently used executable scripts. In Python, I'll always put an __init__.py in my scripts directory so I can run scripts as packages (i.e. python -m scripts.some_scripts) and load modules from sister directories. Based off this as well as googling, I'm starting to get the feeling that this is an anti-pattern.

也就是说,给定如下结构:

That said, given a structure like:

project_dir/
    some_modules_dir/
        foo.py
        bar.py
        ...
    scripts/
        some_script.py
        other_script.py
        ...

运行脚本的正确方法是什么?让它们从其姊妹目录some_modules_dir 导入的正确方法是什么?哪些目录应该包含 __init__.py 哪些不应该?我想尽可能地遵循PEP8,并尽可能地简化运行脚本.如果根本不建议使用脚本目录,那么你们会怎么做?

What's the right way to run scripts and what's the right way to have them import from their sister directory some_modules_dir? Which dirs should contain __init__.py and which shouldn't? I want to follow PEP8 as much as possible, and want to simplify running scripts as much as possible. If having a scripts directory at all is inherently inadvisable, what do you guys do instead?

推荐答案

问题中的链接仅说明运行驻留在包目录中的脚本,这是一个潜在的问题,因为......包不是脚本,脚本也不是包.它们服务于不同的目的并且以不同的方式被调用,所以如果你将它们混合在一起,在某些时候就会变得一团糟.

The link in the question only says about running scripts that reside in a package directory which is a potential problem because... well... packages are not scripts and scripts are not packages. They serve different purposes and are invoked in different ways, so if you mix them together, there'll be a mess at some point.

由于 Python 本身 多年来一直有一个 Scripts 目录并且没有人抱怨,因此它绝不是一种反模式.

Since Python itself has had a Scripts directory for ages and no one complains, it's in no way an anti-pattern.

参见 怎么做我将我的可执行文件与我的库文件分开? 关于我上次工作时我们如何处理可执行脚本.它从未引起我意识到的任何问题.

See How do I separate my executable files from my library files? on how we dealt with executable scripts at my last occupation. It never caused any problems that I'm aware of.

这篇关于Scripts 目录是 Python 中的反模式吗?如果是这样,导入的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 01:03