Py to pyc linux

How to Compile Code to Convert py to pyc in Python?

Whenever you run the Python code, there are two major steps involved.

  • The code (from .py file) gets compiled into byte code and save it as a .pyc file.
  • Byte code from this file gets interpreted.

Python is called as a Byte code interpreted programming language.

This complete process happens in the background so that you don’t see the .pyc file.

This is the usual case when you simply execute any Python program.

py vs pyc file in Python:

If you open any py file, you can see the Python code which is human readable. Whereas, pyc file contains byte code. You can not read it simply.

Now, our interest is to convert the py file into pyc file. For this, you have to compile Python py file without executing it.

When does .pyc file get created?

We import modules in our program. If you are importing module first time, Python compiles the module code and create .pyc file. It is nothing but the bytecode file.

In another scenario, if there is any change in code, python compiles the code and save it as bytecode ( .pyc file) before running a python script.

The .pyc file is created in the same folder where the .py file exists.

These are all usual ways, Python compiles and generates the .pyc file.

Why does compiling .py to .pyc not happen?

In certain scenarios, Python does not generate the .pyc file.

This may occur in case you don’t have write permissions for the directory where you are compiling the code. It can also happen when you don’t have enough space to store bytecode ( .pyc file).

In this case, if you are running Python code, it may run existing (old) .pyc bytecode. This is the worst behavior to trace.

I still remember when I faced this issue. I was updating my code in a python script, but when I run the code, I was amazed not to see any changes in output even after doing changes in the Python script.

And here is a way to get rid of it.

Convert py to pyc in Python by Compiling without Executing

So let’s see how to create a .pyc file just with a simple command.

Читайте также:  Linux ubuntu какая файловая система

For this, you can use two modules for compiling Python script- py_compile and compileall modules.

Method 1: using py_compile module

Import py_compile in your python code. There is a function called compile() . Pass the Python file name that you want to compile as an argument. It will convert Python script into the bytecode (file with the file extension pyc ).

import py_compile py_compile.compile('abc.py')

This will compile the abc.py file and saved compiled bytecode in abc.pyc file. Python stores bytecode in the same directory where the abc.py file exists.

Method 2: using compile all module

Sometimes you may need to compile all the python script within a given directory. Then this method is good rather than compiling each file independently.

In that case, run the following command in a given directory.

It will compile all the files in the current directory.

If you are not providing any of the directories in command, it compiles all the python script found in sys.path.

Note, it will just compile Python py file without executing.

In this post, I have not covered anything related to compiler and interpreter as it is not the scope of this article. If you are interested, you can read the difference between Compiler and Interpreter.

This is all about how to convert py to pyc in Python. If you have any doubt, write in the comment.

Источник

How to make a .pyc file from Python script [duplicate]

I know that when Python script is imported in other python script, then a .pyc script is created. Is there any other way to create .pyc file by using linux bash terminal?

I think you should try to use ‘zipfile’ to make pyc. It’s so easy to make it. You can use it to deploy your code by no src.

2 Answers 2

Use the following command:

This will create your_script.pyc file in the same directory.

You can pass directory also as :

This will create .pyc files for all .py files in the directory

Other way is to create another script as

import py_compile py_compile.compile("your_script.py") 

It also create the your_script.pyc file. You can take file name as command line argument

You could use the py_compile module. Run it from command line ( -m option):

When this module is run as a script, the main() is used to compile all the files named on the command line.

$ tree . └── script.py 0 directories, 1 file $ python3 -mpy_compile script.py $ tree . ├── __pycache__ │ └── script.cpython-34.pyc └── script.py 1 directory, 2 files 

compileall provides similar functionality, to use it you’d do something like

Читайте также:  Astra linux пароль от admin

Where . are files to compile or directories that contain source files, traversed recursively.

Another option is to import the module:

$ tree . ├── module.py ├── __pycache__ │ └── script.cpython-34.pyc └── script.py 1 directory, 3 files $ python3 -c 'import module' $ tree . ├── module.py ├── __pycache__ │ ├── module.cpython-34.pyc │ └── script.cpython-34.pyc └── script.py 1 directory, 4 files 

-c ‘import module’ is different from -m module , because the former won’t execute the if __name__ == ‘__main__’: block in module.py.

Источник

Как я могу вручную создать файл .pyc из файла .py

По какой-то причине я не могу зависеть от оператора «import» Python для автоматического создания файла .pyc. Есть ли способ реализовать функцию следующим образом?

def py_to_pyc(py_filepath, pyc_filepath): . 

7 ответов

Вы можете использовать compileall в терминале. Следующая команда перейдет рекурсивно в подкаталоги и сделает файлы pyc для всех найденных файлов python. Модуль compileall является частью стандартной библиотеки python, поэтому вам не нужно устанавливать что-либо дополнительное для ее использования. Это работает точно так же для python2 и python3.

Это должен быть принятый ответ — по крайней мере, мне нужно собрать все * .py в * .pyc: рекурсивно 🙂

Можно ли распространять PYC-файл, содержащий все используемые библиотеки? Таким образом, пользователям не нужно устанавливать их, просто запустил PYC-файл, я знаю, что в java это возможно с использованием JAR-файлов. Есть ли какой-либо подобный метод для Python?

Я также слышал кое-что о метафайлах в Python. Этот компилятор также собирает какой-то кеш? Если нет, то какая команда для этого? Поскольку конечные пользователи не имеют разрешения на запись в каталог lib. И я хочу ускорить ситуацию здесь . PS. также обратите внимание на флаг -O для компиляции байт-кода (.pyo file iso .pyc).

будьте осторожны с этой командой. Я случайно сделал compileall на моей папке site-packages, и она все испортила

Я использую Anaconda из Python. Он находится в подпапке ProgramData, где я не хочу хранить свои файлы .py. Как я могу использовать эту команду для компиляции определенной папки?

Прошло некоторое время с тех пор, как я последний раз использовал Python, но считаю, что вы можете использовать py_compile :

import py_compile py_compile.compile("file.py") 

Вы, вероятно, хотите включить второй параметр, который определяет выходной файл. В противном случае по умолчанию используется что-то вроде __pycache__/file.cpython-32.pyc и вы получите это в качестве возвращаемого значения.

Вы можете скомпилировать отдельные файлы из командной строки с помощью

python -m compileall .py .py 

Я нашел несколько способов компилировать скрипты Python в байт-код

import py_compile py_compile.compile('YourFileName.py') 
import py_compile py_compile.main(['File1.py','File2.py','File3.py']) 
python -m py_compile File1.py File2.py File3.py . 
python -m py_compile - File1.py File2.py File3.py . . . 
import compileall compileall.compile_dir(direname) 
import compileall compileall.compile_file('YourFileName.py') 

Источник

Читайте также:  Langpack ru puppy linux

How to run a .pyc (compiled python) file?

When I compile a python file, I get a *.pyc file. When I try to run that, I get a message saying there is no program for running them. When I search for a program online via that option, it says there are none. Can anyone help me run there files?

4 Answers 4

Since your python file is byte compiled you need to run it through the python interpreter

The reason you can run your .py files directly is because you have the line

or something similar on the first line in the .py files. This tells your shell to execute the file with the Python interpreter.

To complement this answer: a .pyc file is not compiled in the strictest sense of the term, as it is not native machine code. It is, as @tomdachi wrote, python-specific byte-code (very similar to a Java .class), that’s why it still needs the python interpreter to execture.

in fact, the pyc only was generated when you import the py file. so it is useless to run the pyc file!

To decompile compiled .pyc python3 files, I used uncompyle6 in my current Ubuntu OS as follows:

    Installation of uncompyle6:

uncompyle6 -o . your_filename.pyc 

Python compiles the .py files and saves it as .pyc files so it can reference them in subsequent invocations. The .pyc contain the compiled bytecode of Python source files, which is what the Python interpreter compiles the source to. This code is then executed by Python’s virtual machine. There’s no harm in deleting them (.pyc), but they will save compilation time if you’re doing lots of processing.

Python is an interpreted language, as opposed to a compiled one, though the distinction can be blurry because of the presence of the bytecode compiler. Compiling usually means converting to machine code which is what runs the fastest. But interpreters take human-readable text and execute it. They may do this with an intermediate stage.

For example, When you run myprog.py source file, the python interpreter first looks to see if any myprog.pyc exists (which is the byte-code compiled version of myprog.py ), and if it is as recent or more recent than myprog.py . If so, the interpreter runs it. If it does not exist, or myprog.py is more recent than it (meaning you have changed the source file), the interpreter first compiles myprog.py to myprog.pyc .

There is one exception to the above example. If you put #! /usr/bin/env python on the first line of myprog.py , make it executable, and then run myprog.py by itself.

Источник

Оцените статью
Adblock
detector