Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is .pyc file created sometimes in same directory and sometimes in __pycache__ subdirectory?

I am using Windows 7 and have both Python 2.7.5 and 3.3.2 installed. My path environment variable is set as

C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\python27;C:\Python33\Scripts

When I import any Python module into another module a .pyc file is created. The place where it is created depends on whether Python2 is invoked or Python3 to run it.

  • when I double-click the module the .pyc file is created in the same directory
  • when I am editing via IDLE and then run it then the file is created in the subdirectory.
  • If I add #! Python3 at the top then double-clicking makes the .pyc file in the sub-directory.

I understand that the reason for this is because of difference in how Python2 and Python3 have decided to manage the byte-compiled codes.

I am currently focusing on Python3 and want the files to be created in subdirectory only.

I tried editing the path variable to place Python3 before Python 2 so that Python3 should be invoked instead of Python2. Even after changing it when I double-click the Python script that didn't happen and the byte-compiled code was created in the same directory.

So Python2 was used to run the Python script on double-clicking. What is causing this behaviour and how can I make sure that Python3 is invoked instead of Python2 without uninstalling Python2?

like image 290
Aseem Bansal Avatar asked Dec 05 '25 10:12

Aseem Bansal


1 Answers

Python 3 has changed how the bytecode (.pyc) files are stored. Python 2 uses the convention of putting them in the same directory, but for Python 3 the developers decided to reduce clutter by putting them all in a separate directory. This also made support for Python implementations other than CPython easier, as each implementation could have its own .pyc files in the __pycache__ directory rather than overwriting those from other implementations.

like image 69
Abe Karplus Avatar answered Dec 06 '25 23:12

Abe Karplus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!