简体   繁体   English

在Python 3.x中避免使用.pyc文件?

[英]Avoid .pyc Files in Python 3.x?

Currently, I'm working with Python 3.4. 目前,我正在使用Python 3.4。 How could I avoid .pyc or .pyo files ( __pycache__ ) without editing the commandline? 如何在不编辑命令行的情况下避免使用.pyc.pyo文件( __pycache__ )?

The following command works perfectly Using terminal: python3 -B something.py 以下命令在使用终端时效果很好: python3 -B something.py

But these are not working in Python 3 (or are they??): 但是这些在Python 3中不起作用(或者它们是?):

import os

os.environ['PYTHONDONTWRITEBYTECODE'] = "whatever"

according to the instructions , if it is set to a non-empty string, it should work. 根据说明 ,如果将其设置为非空字符串,则应该可以使用。 But I couldn't. 但是我不能。

What am I missing? 我想念什么?

I believe that environment variable must be set before the Python interpreter starts. 我认为必须在Python解释器启动之前设置环境变量。 Setting it from within a Python script seems to be too late (the interpreter has already loaded the script and generated the bytecode file). 从Python脚本中设置它似乎为时已晚(解释器已经加载了脚本并生成了字节码文件)。

The environment variable is read by the executable when it starts up. 可执行文件在启动时会读取环境变量。 Setting it in the script can have no effect for the current interpreter. 在脚本中设置它对当前解释器无效。 You must do it before the executable is run. 您必须先执行此操作,然后才能运行可执行文件。

  • Python 3 will create __pycache__ directories with version-related compiled python inside. Python 3将使用__pycache__与版本相关的已编译python创建__pycache__目录。 .pyc is from Python 2. .pyc来自Python 2。

  • You do need to specify this on the command line OR in the environment while starting python, not after. 您确实需要在启动python时(而不是之后)在命令行OR或环境中指定此选项。 But if you are writing an executable script in an environment that supports shebang lines, you can do something like: 但是, 如果要在支持shebang行的环境中编写可执行脚本,则可以执行以下操作:

#!/usr/bin/env python3 -B
  • Since your question specifies "without using the command line", you could set the PYTHONDONTWRITEBYTECODE=1 environment variable for your system/shell. 由于您的问题指定“不使用命令行”, 因此可以为系统/ shell设置PYTHONDONTWRITEBYTECODE=1环境变量。

check this .. set env variable before executing export PYTHONDONTWRITEBYTECODE="" set this in .bashrc or alias python3="python3 -B" 在执行导出PYTHONDONTWRITEBYTECODE =“”之前检查此.. set env变量。“在.bashrc或别名python3 =” python3 -B“中进行设置

.. How to avoid .pyc files? .. 如何避免.pyc文件?

but you will get pycache folder for python3 in the imported module level 但是您将在导入的模块级别获得python3的pycache文件夹

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM