自解压并在python中执行代码 [英] Self decompressing and executing code in python

查看:271
本文介绍了自解压并在python中执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是创建包含任意python代码的压缩文件的代码.这个想法是,您将某种python程序粘贴到raw_code变量赋值中,然后运行脚本以创建一个.py文件,该文件是功能性python代码,它将打开另一个python shell,并执行其中存储的压缩代码.

This is the code that creates a compressed file with arbitrary python code in it. The idea is that you paste some kind of python program in the raw_code variable assignment, then run the script which creates a .py file which is functional python code that opens another python shell and executes the compressed code stored within it.

import zlib

raw_code = """print 'hello world' """

code_prefix = """import zlib
import os

compressed_code = \"\"\"
"""

code_postfix = """
\"\"\"

os.system('python ' + zlib.decompress(compressed_code))
"""

full_code = code_prefix + zlib.compress(raw_code) + code_postfix


with open("/some/kind/of/path/compCode.py", "wb") as outfile:
    outfile.write(full_code)

从中获取的文件如下所示:

the file you get from this looks like this:

import zlib
import os

compressed_code = """
x��*(��+QP�H���W(�/�IQ�N�
"""

os.system('python ' + zlib.decompress(compressed_code))

我遇到的问题是尝试运行第二个文件会导致错误:

The problem I'm running into is that trying to run the second file results in an error:

  File "compCode.py", line 6
SyntaxError: Non-ASCII character '\x9c' in file compressedPYCode.py on line 7, 
but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

在compressed_code变量之前添加"r"无济于事.我试图做的事实际上有可能吗?

adding an 'r' before the compressed_code variable doesn't help. Is what I'm trying to do actually possible?

推荐答案

尝试将# -*- coding: utf-8 -*-放在脚本的第一行.

Try putting # -*- coding: utf-8 -*- on the first line of your script.

您可能可以强制编码以正确加载字符串,但里程可能会有所不同.如果您在字符串中包含空字节或其他内容,显然将无法正确存储.

You may be able to force your encoding to get your string to load correctly but mileage may vary. If you have null bytes or something in the string they're obviously not going to be stored correctly.

这篇关于自解压并在python中执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆