-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_interpreter.py
More file actions
59 lines (57 loc) · 2.33 KB
/
python_interpreter.py
File metadata and controls
59 lines (57 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import sys
import code
import os
def execute_command(cmd):
try:
exec(cmd)
except Exception as e:
print(f"Error executing the command: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) > 1:
# Check if the first argument is "-u" (unbuffered output)
if sys.argv[1] == "-u":
# -u flag means unbuffered output, skip it and process the next argument
if len(sys.argv) > 2:
arg = sys.argv[2]
if os.path.isfile(arg):
try:
# If a script file is provided as an argument, execute it
exec(open(arg).read())
except Exception as e:
print(f"Error executing the script: {e}", file=sys.stderr)
sys.exit(1)
else:
# If the argument is not a file, treat it as a Python command
execute_command(arg)
else:
# No arguments after -u, start interactive interpreter
print("Python " + sys.version)
print("Type 'exit()' or 'quit()' to exit the interpreter.")
code.interact(local=locals())
# Check if the first argument is "-c"
elif sys.argv[1] == "-c":
# Ensure there is a code argument after "-c"
if len(sys.argv) > 2:
code_to_run = sys.argv[2]
execute_command(code_to_run)
else:
print("Error: '-c' flag provided but no code given", file=sys.stderr)
sys.exit(1)
else:
arg = sys.argv[1]
if os.path.isfile(arg):
try:
# If a script file is provided as an argument, execute it
exec(open(arg).read())
except Exception as e:
print(f"Error executing the script: {e}", file=sys.stderr)
sys.exit(1)
else:
# If the argument is not a file, treat it as a Python command
execute_command(arg)
else:
# No arguments provided, start an interactive interpreter
print("Python " + sys.version)
print("Type 'exit()' or 'quit()' to exit the interpreter.")
code.interact(local=locals())