Python Tricks
Code Injection
When standard import os; os.system("bash") doesn't work, use dynamic import:
__import__('os').system('bash')
Python 2 → 3 (2to3)
2to3 -w script.py
Key changes to watch for:
| Area | Python 2 | Python 3 |
|---|---|---|
print "Hello" | print("Hello") | |
| Unicode strings | u"hello" | "hello" (default) |
| Byte strings (send) | s.send(data) | s.send(data.encode()) |
| Byte strings (recv) | data = s.recv(1024) | data = s.recv(1024).decode() |
| Integer division | 5 / 2 → 2 | 5 / 2 → 2.5, use // for int |
| Ranges | xrange(5) | range(5) |
| Input | raw_input("...") | input("...") |
| Exceptions | except Exception, e: | except Exception as e: |
| Dict iteration | dict.iteritems() / iterkeys() | dict.items() / keys() |
| Large ints | long type | int handles automatically |