Last active
March 11, 2016 17:55
-
-
Save Plutor/7a3f0d5ad415be597799 to your computer and use it in GitHub Desktop.
Generate random perl for http://twitter.com/ThisIsPerl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import os | |
import random | |
import shutil | |
import subprocess | |
import sys | |
import tempfile | |
perl_binary = '/usr/bin/perl' | |
min_length = 15 | |
max_length = 35 | |
max_tries = 10000 | |
max_to_generate = 50 | |
valid_chars = (['LETTER'] * 3) + (['DIGIT'] * 3) + [ | |
' ', '!', '$', '%', '&', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', | |
'<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', | |
'~', '\n'] | |
valid_letters = [chr(v) for v in range(97, 123)] | |
valid_digits = [chr(v) for v in range(48, 58)] | |
dest_file = sys.argv[1] if len(sys.argv) > 1 else '' | |
FNULL = open(os.devnull, 'w') | |
with tempfile.NamedTemporaryFile() as tf: | |
for i in range(max_tries): | |
length = random.randrange(min_length, max_length) | |
script = '' | |
for _ in range(length): | |
script = script + random.choice(valid_chars) | |
# Replace LETTER and DIGIT. | |
oldscript = '' | |
while oldscript != script: | |
oldscript = script | |
script = script.replace( | |
'LETTER', random.choice(valid_letters), 1).replace( | |
'DIGIT', random.choice(valid_digits), 1) | |
# Filter out: | |
# Start with = | |
if script[0] == '=': | |
continue | |
# Start and end with <> | |
if script[0] == '<' and script[-1] == '>': | |
continue | |
# Start and end with the same character (catches `` and ?? and others) | |
if script[0] == script[-1]: | |
continue | |
failed = subprocess.call([perl_binary, '-c', '-e', script], | |
stdout=FNULL, stderr=FNULL) | |
if failed == 0: | |
if dest_file: | |
tf.write(script.replace('\n', '\\n')) | |
tf.write('\n') | |
else: | |
print script.replace('\n', '\\n') | |
max_to_generate -= 1 | |
if max_to_generate == 0: | |
sys.exit(0) | |
# Copy temp file to sys.argv[1] | |
if dest_file: | |
tf.flush() | |
print 'Copying %s to %s' % (tf.name, dest_file) | |
shutil.copy(tf.name, dest_file) | |
os.chmod(dest_file, 0644) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment