python如何执行代码_自解压并在python中执行代码

1586010002-jmsa.png

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

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

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值