Advertisement
pantteri

Self-generating code (sub optimal)

Jan 3rd, 2013
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. import os, random, traceback
  2.  
  3. # Select two random files from the folder this file is in and read them. Make sure there are at least two files. This will work best if all files are executable python programs.
  4. a, b = random.sample(os.listdir(os.path.dirname(os.path.realpath(__file__))), 2)
  5. a = open(a).read()
  6. b = open(b).read()
  7.  
  8. # Loop until an executable program is found
  9. while 1:
  10.    
  11.     # Combinate the two files randomly
  12.     ai = 1
  13.     bi = 1
  14.     s = ''
  15.     while ai < len(a) or bi < len(a):
  16.        
  17.         # Append one byte at time
  18.         if bi == len(b) or ai < len(a) and random.getrandbits(1):
  19.             s += a[ai-1]
  20.             ai += 1
  21.         else:
  22.             s += b[bi-1]
  23.             bi += 1
  24.  
  25.     # After combining two files successfully, try executing new code
  26.     try:
  27.         exec(s)
  28.         # If the execution happens to be successful, print the code and exit
  29.         print s
  30.         break
  31.     except:
  32.         # Most likely the execution will fail. Try again.
  33.         traceback.print_exc()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement