Created
February 10, 2019 00:00
-
-
Save recolic/6e2355281da9b27464568c3b09a3b0e7 to your computer and use it in GitHub Desktop.
Run python3 in a python2 code.
This file contains 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
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