Created
November 12, 2019 05:23
-
-
Save shiracamus/c2c216f35c94bfbe11ae4df4558c9d1f to your computer and use it in GitHub Desktop.
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
import os | |
import sys | |
import subprocess | |
import tempfile | |
def autopep8(code): | |
with tempfile.NamedTemporaryFile('w', delete=False) as f: | |
f.write(code) | |
code_file_name = f.name | |
subprocess.run(['autopep8', '-i', code_file_name]) | |
with open(code_file_name) as f: | |
code = f.read() | |
os.unlink(code_file_name) | |
return code | |
def autopep8markdown(lines): | |
in_code_block = False | |
for line in lines: | |
if not in_code_block: | |
yield line | |
if '```py' in line: | |
in_code_block = True | |
code = '' | |
else: | |
if '```' not in line: | |
code += line | |
else: | |
yield autopep8(code) | |
yield line | |
in_code_block = False | |
def input_lines(): | |
if len(sys.argv) == 1: | |
return sys.stdin.readlines() | |
else: | |
return open(sys.argv[1]).readlines() | |
def output_lines(lines): | |
for line in lines: | |
print(line, end='') | |
def main(): | |
output_lines(autopep8markdown(input_lines())) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment