Jump to content
Korean Random
IzeBerg

Как и чем декомпилировать/компилировать питон?

Recommended Posts

Собственно вопрос припёк меня давно. Есть-ли какие-то утилиты/способы декомпилировать и компилировать *.pyc файлы?

P.s. Гугл не помог, кидал в какие-то онлайн-декомпиляторы, но там ограничение 10кб.

Edited by IzeBerg

Share this post


Link to post

Short link
Share on other sites

Гугл помог, первая и вторая ссылка у меня, например.

  • Upvote 7
  • Downvote 6

Share this post


Link to post

Short link
Share on other sites

Гугл помог, первая и вторая ссылка у меня, например.

А ссылки эти можно? Просто я уже не первый день ищу.

depython.net не катит, там ограничение

Edited by IzeBerg

Share this post


Link to post

Short link
Share on other sites

Гугл помог, первая и вторая ссылка у меня, например.

Так если вы авторизованы в гугле, результаты поиска строятся по вашим увлечениям, могло и не выдать человеку)

Share this post


Link to post

Short link
Share on other sites

Неа не помогло. Нашел какие-то декомпиляторы, но никакой инструкции к ним нет, через коммандную строку рыл их ихние команды, ничего про декомпиляцию не сказано.

Share this post


Link to post

Short link
Share on other sites

Где-то уже была тема по декомпиляторам питона в разделе, но не могу найти) Вот декомпиляторы Python которые удалось вспомнить. 

 

https://github.com/Mysterie/uncompyle2

https://code.google.com/p/unpyc3/

https://github.com/gstarnberger/uncompyle

https://code.google.com/p/unpyc/

http://sourceforge.net/projects/easypythondecompiler/

  • Upvote 1

Share this post


Link to post

Short link
Share on other sites

А есть где нибудь гайдик как ими пользоваться?

Share this post


Link to post

Short link
Share on other sites

А есть где нибудь гайдик как ими пользоваться?

Там с сорцами есть сопутствующая дока. Вот например для uncompyle2: https://github.com/Mysterie/uncompyle2/blob/master/README.rst

uncompyle2 
==========

A Python 2.5, 2.6, 2.7 byte-code decompiler, written in Python 2.7

Introduction
------------

'uncompyle2' converts Python byte-code back into equivalent Python
source code. It accepts byte-code from Python version 2.5 to 2.7. 
Additionally, it will only run on Python 2.7.

The generated source is very readable: docstrings, lists, tuples and
hashes get pretty-printed.

'uncompyle2' is based on John Aycock's generic small languages compiler
'spark' (http://www.csr.uvic.ca/~aycock/python/) and his prior work on
a tool called 'decompyle'. This tool has been vastly improved by
Hartmut Goebel `http://www.crazy-compilers.com/`_

# Additional note (3 July 2004, Ben Burton):

This software is no longer available from the original website. It has
now become a commercial decompilation service, with no software
available for download.

Any developers seeking to make alterations or enhancements to this code
should therefore consider these debian packages an appropriate starting
point.

# Additional note (5 June 2012):

The decompilation of python bytecode 2.5 & 2.6 is based on the work of
Eloi Vanderbeken. bytecode is translated to a pseudo 2.7 python bytecode
and then decompiled.

Features
--------

- decompiles Python byte-code into equivalent Python source
- decompiles byte-code from Python version 2.5, 2.6, 2.7
- pretty-prints docstrings, hashes, lists and tuples
- reads directly from .pyc/.pyo files, bulk-decompile whole directories
- output may be written to file, a directory or to stdout
- option for including byte-code disassembly into generated source

For a list of changes please refer to the 'CHANGES' file.


Requirements
------------

uncompyle2 requires Python 2.7


Installation
------------

You may either create a RPM and install this, or install directly from
the source distribution.

Creating RPMS:

    python setup.py bdist_rpm

If you need to force the python interpreter to eg. pyton2:

    python2 setup.py bdist_rpm --python=python2

### Installation from the source distribution:

    python setup.py install

To install to a user's home-dir:

    python setup.py install --home=<dir>

To install to another prefix (eg. /usr/local)

    python setup.py install --prefix=/usr/local

For more information on 'Installing Python Modules' please refer to
http://www.python.org/doc/current/inst/inst.html


Usage
-----

./uncompyle2.py -h		prints usage

./test_pythonlib.py		test files and python library

Known Bugs/Restrictions
-----------------------

No support for python 3.2

It currently reconstructs most of Python code but probably needs to be tested more thoroughly. All feedback welcome

Share this post


Link to post

Short link
Share on other sites

А как компилировать обратно декомпилиованные файлы для WoT? Использую py_compile/compileall в Python 2.7, но на полученные файлы WoT ругается. Что не так?

 

ImportError: scripts/client/[файл].pyc is not a valid Python compiled module file

 

Share this post


Link to post

Short link
Share on other sites

Знающие, напишите небольшой гайдик по компиляции-декомпиляции, я вот ну никак к этому питону подкопаться не могу, а так бы начал хотя бы по аналогии делать.

Share this post


Link to post

Short link
Share on other sites

Знающие, напишите небольшой гайдик по компиляции-декомпиляции, я вот ну никак к этому питону подкопаться не могу, а так бы начал хотя бы по аналогии делать.

Присоединяюсь к просьбе.

Share this post


Link to post

Short link
Share on other sites

Знающие, напишите небольшой гайдик по компиляции-декомпиляции, я вот ну никак к этому питону подкопаться не могу, а так бы начал хотя бы по аналогии делать.

1. Скачиваешь питон 2.7.http://www.python.org/ftp/python/2.7.5/python-2.7.5.msi

2. Устанавливаешь питон в папку скажем C:\Python27

3. Добавляешь папку с питоном в переменную среды Path

post-16733-0-02366300-1381599876_thumb.png

post-16733-0-32670000-1381599894_thumb.png

4. Скачиваешь uncompyle2 https://github.com/Mysterie/uncompyle2/archive/master.zip

5. Распаковываешь ее в скажем c:\uncompyle2

6. Открываешь командную строку и переходишь в папку с uncompyle2 

cd c:\uncompyle2

7. устанавливаем утилиту выполнив в командной строке

python setup.py install

8. если все ок у нас должны появится папки build и в ней папка scripts-2.7 в которой лежит собственно сама утилита файл uncompyle2

9. берем интересующий нас скрипт например cameranode.pyc и кладем его в папку c:\uncompyle2\build\scripts-2.7\

10. открываем командную строку и переходим в ней в папку со скриптом

cd c:\uncompyle2\build\scripts-2.7\

11. переводим скрипт из бинарика в исходный вид:

python uncompyle2 -o cameranode.py cameranode.pyc

Вот собственно и вся декомпиляция слог у меня чугунный но вроде достаточно понятно изложил....

 

 

Теперь немного по поводу компиляции скриптов. В клиенте использована  более ранняя версия 2.6 поэтому компилировать будем в нем, ранее установленная версия для этого не подойдет.

1. Скачиваем Python 2.6 http://www.python.org/download/releases/2.6/

2. Устанавливаем его в папку C:\Python26\

3.Выбираем скрипт который мы будем редактировать

post-16733-0-61583200-1381599155_thumb.png

4. Убеждаемся что скрипт открылся именно в версии 2.6

post-16733-0-46846500-1381599271_thumb.png

5. Вносим необходимые изменения в скрипт и пытаемся выполнить

post-16733-0-71513600-1381599385_thumb.png

6. Попадаем в окно интерпретатора, который должен жаловатся на отсутсвие модуля BigWorld других ошибок быть НЕ ДОЛЖНО иначе правим свой скрипт

post-16733-0-76634200-1381599533_thumb.png

7. В папке с исходным скриптом который мы редактировали должен появится компилированный скрипт с расширением pyc его можно закидывать в клиент

 

 

Edited by jeroohn
  • Upvote 15

Share this post


Link to post

Short link
Share on other sites

Ах да, забыл сказать что uncompyle2 прекрасно разбирает все оригинальные скрипты, но не всегда справляется с модифицированными файлами, для их разборки есть другая утилита pycdc

Share this post


Link to post

Short link
Share on other sites
у меня uncompyle2 обломался на arcadecamera.pyc и strategiccamera.pyc из версии 0.8.8

 

Действительно обламывается pycdc разобрал напутав с цифрами...

Edited by jeroohn
  • Upvote 1

Share this post


Link to post

Short link
Share on other sites

6. Попадаем в окно интерпретатора, который должен жаловатся на отсутсвие модуля BigWorld других ошибок быть НЕ ДОЛЖНО иначе правим свой скрипт

Неверно. Питон - интерпретируемый язык, поэтому если даже дальше в коде есть ошибки, все равно это не отобразится.

Edited by Axon555
  • Upvote 1

Share this post


Link to post

Short link
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...