Skip to content

Commit e987932

Browse files
committed
Add prototype of compiler
1 parent f08eaca commit e987932

File tree

3 files changed

+89
-1
lines changed

3 files changed

+89
-1
lines changed

.editorconfig

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
root = true
2+
3+
[*]
4+
charset = utf-8
5+
end_of_line = lf
6+
indent_style = space
7+
indent_size = 4
8+
insert_final_newline = true
9+
trim_trailing_whitespace = true

README.md

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,24 @@
1-
# python-compiler
1+
# Python Compiler
2+
23
Just simply compile *.py to *.pyc
4+
5+
## Usage
6+
7+
```bash
8+
python compiler.py main.py
9+
```
10+
11+
```bash
12+
python compiler.py program_directory
13+
```
14+
15+
Using `-h` flag to show more detail about arguments
16+
17+
## Using file after compiling
18+
19+
Using `pyc` file instead of `py` file.
20+
Example: After compile `hello.py` to `hello.pyc`, we using this command to run the script.
21+
22+
```bash
23+
python hello.pyc
24+
```

compiler.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
2+
from pathlib import Path
3+
import os
4+
import py_compile
5+
6+
7+
def compile_file(source_file: Path, delete=False) -> bool:
8+
target_file = str(source_file) + 'c'
9+
try:
10+
ok = py_compile.compile(source_file, target_file)
11+
if delete:
12+
source_file.unlink()
13+
except py_compile.PyCompileError as err:
14+
print(f'*** Error compiling {source_file}...')
15+
# escape non-printable characters in msg
16+
encoding = sys.stdout.encoding or sys.getdefaultencoding()
17+
msg = err.msg.encode(encoding, errors='backslashreplace').decode(encoding)
18+
print(msg)
19+
return False
20+
except (SyntaxError, UnicodeError, OSError) as e:
21+
print(f'*** Error compiling {source_file}...')
22+
print(e.__class__.__name__ + ':', e)
23+
return False
24+
else:
25+
return ok != 0
26+
27+
28+
29+
def main():
30+
import argparse
31+
"""Script main program."""
32+
33+
parser = argparse.ArgumentParser(description='Utilities to compile *.py to *.pyc.')
34+
parser.add_argument('-d', '--delete', action='store_true', dest='delete', default=False, help='delete source files')
35+
parser.add_argument('compile_dests', metavar='FILE|DIR', nargs='*', help='file or directory names to compile')
36+
37+
args = parser.parse_args()
38+
39+
source_files = []
40+
41+
for dest in args.compile_dests:
42+
dest = Path(dest)
43+
if dest.is_file():
44+
source_files.append(dest)
45+
if dest.is_dir():
46+
source_files += list(dest.glob('**/*.py'))
47+
48+
for file in source_files:
49+
compile_file(file, delete=args.delete)
50+
51+
return True
52+
53+
54+
if __name__ == '__main__':
55+
import sys
56+
exit_status = int(not main())
57+
sys.exit(exit_status)

0 commit comments

Comments
 (0)