Python 3“不断发展”的代码

时间:2015-05-08 20:27:14

标签: python python-3.x

我想尝试制作一个不断发展的代码,你知道,只是为了看看我是否可以。

长话短说,我做不到。

__author__ = 'kim'
import random
import string
import fileinput
import os



#Random letter
random_letter = random.choice(string.ascii_letters)
print(random_letter)
#Other Random Letter
other_random_letter = random.choice(string.ascii_letters)
print(other_random_letter)

for line in fileinput.input("file.py", inplace=True):
    print(line.replace(other_random_letter, random_letter), end='')

os.system("python3 file.py")

我想要做的是用乱码替换随机数量的代码。如果代码崩溃,它将从名为fallsafe.py的文件中复制并替换文件file.py

1 个答案:

答案 0 :(得分:0)

我会用exec:

来做
import random
import string

code = ''

for i in range(1000): #1000 iterations
    if random.randint(0, 1):
        code += random.choice(string.ascii_letters)
    else:
        code = random.choice(string.ascii_letters)

    try:
        print ('trying code: ' + code)
        exec(code)
    except:
        print('It crashed... adding another letter... it will surely work now!')

现在,让我告诉你这将永远不会起作用,它几乎不可能产生一个有意义的代码行(顺便说一句,你应该在random.choice中包含空格)。

我知道你想做什么,而我之前已经做过,但你需要一个特殊的虚拟机,只需一个字节命令,这样就可以更容易地生成有效的代码。