什么是 __pycache__? [英] What is __pycache__?

查看:50
本文介绍了什么是 __pycache__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,缓存是类似文件的加密文件.

From what I understand, a cache is an encrypted file of similar files.

我们如何处理 __pycache__ 文件夹?它是我们提供给人们的东西而不是我们的源代码吗?这只是我的输入数据吗?这个文件夹不断被创建,它是做什么用的?

What do we do with the __pycache__ folder? Is it what we give to people instead of our source code? Is it just my input data? This folder keeps getting created, what it is for?

推荐答案

当你在 python 中运行一个程序时,解释器首先将它编译为字节码(这是一种过度简化)并将其存储在 __pycache__ 文件夹.如果您查看那里,您会发现一堆共享项目文件夹中 .py 文件名称的文件,只有它们的扩展名是 .pyc 或 .pyo.它们分别是程序文件的字节码编译版本和优化字节码编译版本.

When you run a program in python, the interpreter compiles it to bytecode first (this is an oversimplification) and stores it in the __pycache__ folder. If you look in there you will find a bunch of files sharing the names of the .py files in your project's folder, only their extensions will be either .pyc or .pyo. These are bytecode-compiled and optimized bytecode-compiled versions of your program's files, respectively.

作为程序员,您基本上可以忽略它......它所做的只是让您的程序启动得更快一点.当您的脚本更改时,它们将被重新编译,如果您删除文件或整个文件夹并再次运行您的程序,它们将重新出现(除非您明确禁止该行为).

As a programmer, you can largely just ignore it... All it does is make your program start a little faster. When your scripts change, they will be recompiled, and if you delete the files or the whole folder and run your program again, they will reappear (unless you specifically suppress that behavior).

当您将代码发送给其他人时,通常的做法是删除该文件夹,但您是否这样做并不重要.当您使用版本控制 (git) 时,此文件夹通常列在忽略文件 (.gitignore) 中,因此不包括在内.

When you're sending your code to other people, the common practice is to delete that folder, but it doesn't really matter whether you do or don't. When you're using version control (git), this folder is typically listed in the ignore file (.gitignore) and thus not included.

如果您正在使用 cpython(这是最常见的,因为它是参考实现)并且您不想要该文件夹,那么您可以通过使用 -B 标志启动解释器来抑制它,例如

If you are using cpython (which is the most common, as it's the reference implementation) and you don't want that folder, then you can suppress it by starting the interpreter with the -B flag, for example

python -B foo.py

另一个选项,如 tcaswell 所指出的,是将环境变量 PYTHONDONTWRITEBYTECODE 设置为任何值(根据 python 的手册页,任何非空字符串").

Another option, as noted by tcaswell, is to set the environment variable PYTHONDONTWRITEBYTECODE to any value (according to python's man page, any "non-empty string").

这篇关于什么是 __pycache__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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