27

I am a complete newb to python, hence a silly question.

As i understand, upon first execution of a *.py program, byte code is created into *.pyc and used until a change in *.py file.

Where might this *.pyc bytecode be found in a project?

I would think bin, but nothing is there

James Raitsev
  • 92,517
  • 154
  • 335
  • 470

4 Answers4

38

A *.pyc file is created for imported modules, and they are placed in the same directory containing the .py file. However... no .pyc file is created for the main script for your program. In other words... if you call "python myscript.py" on the command line, there will be no .pyc file for myscript.py.

This is how Python 2.x behaves. However, in Python 3.x the .pyc files are saved in a __pycache__ directory. See David Glick's answer for details.

[edit: Added note about Python 3.x.]

dappawit
  • 12,182
  • 2
  • 32
  • 26
  • As of Python 3.8 you can set the `-X pycache_prefix=PATH` flag, or the `PYTHONPYCACHEPREFIX` environment variable, to change the location where the .pyc file tree is kept. See [docs](https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPYCACHEPREFIX). – Jadzia626 Aug 24 '21 at 19:49
25

In Python < 3.2, the .pyc files are placed in the same directory as the .py file.

In Python 3.2, the compiled files are placed in a __pycache__ subdirectory, and are named differently depending on which Python interpreter created them. (This can be useful to people importing the same Python modules from multiple versions of Python.) See http://docs.python.org/dev/whatsnew/3.2.html#pep-3147-pyc-repository-directories for more information.

David Glick
  • 5,422
  • 17
  • 23
  • 9
    For future readers who have the confusion I've just resolved: This only applies to *modules*. Your first "Hello, world" script will not have a `.pyc` file written *anywhere*. See [this answer](http://stackoverflow.com/a/27735336/5419599) for explanation. – Wildcard Sep 04 '16 at 16:59
1

They are always created in whatever directory contains your .py files. Also, they are created for imported modules, not files that you directly run.

If you want to create .pyc files, boot up a Python interpreter and just import the modules of your choosing.

Community
  • 1
  • 1
ide
  • 19,942
  • 5
  • 64
  • 106
0

The .pyc files are normally created in the same directory as the files that they correspond to. E.g., both my_file.py and my_file.pyc should be in the same location.

  • I see 2 files next to source folder: .pydevproject and .project. Inside source, i see only .py file – James Raitsev Mar 01 '11 at 02:18
  • There won't necessarily be a .pyc for every file. They are normally created when a module is _imported_ rather than run directly. –  Mar 01 '11 at 02:21