Add "py", a CLI for python one-liners
This commit is contained in:
54
.mgr_config/bin/py
Normal file
54
.mgr_config/bin/py
Normal file
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
source = " ".join(sys.argv[1:])
|
||||
INPUT_SRC_NAME = "<py-input>"
|
||||
|
||||
global_vars = {}
|
||||
local_vars = {}
|
||||
|
||||
py_env_conf = Path.home() / ".py-env.py"
|
||||
if py_env_conf.exists():
|
||||
with open(Path.home() / ".py-env.py") as f:
|
||||
code = compile(f.read(), "py-env.py", "exec")
|
||||
exec(code)
|
||||
|
||||
try:
|
||||
code = compile(source, INPUT_SRC_NAME, "eval")
|
||||
val = eval(code)
|
||||
|
||||
# If it's a string, just print it
|
||||
if type(val) == str:
|
||||
print(val)
|
||||
exit(0)
|
||||
|
||||
# If it's not iterable, just print it
|
||||
try:
|
||||
it = iter(val)
|
||||
except TypeError as e:
|
||||
if val is not None:
|
||||
print(val)
|
||||
exit(0)
|
||||
|
||||
# It's iterable, print each element as a line
|
||||
try:
|
||||
for item in val:
|
||||
print(item)
|
||||
exit(0)
|
||||
except Exception as e:
|
||||
e.args = ("Failed to print all elements",) + e.args
|
||||
raise
|
||||
|
||||
except (SyntaxError, NameError) as e:
|
||||
pass
|
||||
|
||||
try:
|
||||
code = compile(source, INPUT_SRC_NAME, "exec")
|
||||
exec(code)
|
||||
except (SyntaxError, NameError) as e:
|
||||
e.args = ("Invalid Python code",) + e.args
|
||||
raise e
|
||||
Reference in New Issue
Block a user