Skip to content

Commit 150ee76

Browse files
brenns10osandov
authored andcommitted
cli: add -e option to exec() code directly
The Python interpreter has "-c" which allows directly running code provided as a command line argument. This is useful for quick tests, without needing to write a script and execute it, and without needing to run the interactive interpreter. It can also be used in scripts or one-liners. Unfortunately, "-c" is already used in the drgn CLI. However, this functionality would be quite useful. Let's add it to the CLI using the option "-e", which is short for "execute" or "exec", the underlying Python function. Signed-off-by: Stephen Brennan <[email protected]>
1 parent 1b05b8c commit 150ee76

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

drgn/cli.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,12 @@ def _main() -> None:
491491
const="none",
492492
help="don't print any logs or download progress",
493493
)
494+
parser.add_argument(
495+
"-e",
496+
dest="exec",
497+
metavar="CODE",
498+
help="an expression or statement to evaluate, instead of running in interactive mode",
499+
)
494500
parser.add_argument(
495501
"script",
496502
metavar="ARG",
@@ -502,7 +508,7 @@ def _main() -> None:
502508

503509
args = parser.parse_args()
504510

505-
if args.script:
511+
if args.script and not args.exec:
506512
# A common mistake users make is running drgn $core_dump, which tries
507513
# to run $core_dump as a Python script. Rather than failing later with
508514
# some inscrutable syntax or encoding error, try to catch this early
@@ -518,7 +524,7 @@ def _main() -> None:
518524
)
519525
elif script_type == "elf":
520526
sys.exit(f"error: {args.script[0]} is a binary, not a drgn script")
521-
else:
527+
elif not args.exec:
522528
print(version, file=sys.stderr, flush=True)
523529

524530
if args.log_level == "none":
@@ -564,7 +570,11 @@ def _main() -> None:
564570

565571
_load_debugging_symbols(prog, args, color)
566572

567-
if args.script:
573+
if args.exec:
574+
sys.path.insert(0, "")
575+
sys.argv = ["-e"] + args.script
576+
exec(args.exec, default_globals(prog))
577+
elif args.script:
568578
sys.argv = args.script
569579
script = args.script[0]
570580
if pkgutil.get_importer(script) is None:

0 commit comments

Comments
 (0)