Skip to content

Instantly share code, notes, and snippets.

@recolic
Created February 10, 2019 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save recolic/6e2355281da9b27464568c3b09a3b0e7 to your computer and use it in GitHub Desktop.
Save recolic/6e2355281da9b27464568c3b09a3b0e7 to your computer and use it in GitHub Desktop.
Run python3 in a python2 code.
import tempfile, subprocess
def py3in2(func_text, arg):
# escape char in arg should be escaped twice.
payload = ['#/usr/bin/env python3', 'def _func(arg):']
for line in func_text.split('\n'):
payload.append(' ' + line)
payload.append('with open("/dev/fd/1", "w") as f:\n f.write(_func(\''+arg+'\'))\n')
payload = '\n'.join(payload)
with tempfile.NamedTemporaryFile() as tf:
tf.file.write(payload)
tf.file.close()
output = subprocess.check_output(["python3", tf.name], stderr=subprocess.PIPE)
return output
ret = py3in2('''
import sys
return sys.version
''', '')
print ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment