Skip to content

Commit

Permalink
run: Edit sys.path before running args.script
Browse files Browse the repository at this point in the history
This enables finding local modules. Also, ensure that `sys.argv[0]`
matches what it would if the user had run this command without Memray,
to minimize the observeable differences our runner forces on users'
scripts.

Signed-off-by: tal66 <77445020+tal66@users.noreply.github.com>
Signed-off-by: Matt Wozniski <mwozniski@bloomberg.net>
  • Loading branch information
tal66 authored and godlygeek committed May 13, 2022
1 parent 802b8f4 commit fb510a2
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/memray/commands/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,6 @@ def _run_tracker(
post_run_message: Optional[str] = None,
follow_fork: bool = False,
) -> None:
sys.argv = [args.script, *args.script_args]
if args.run_as_module:
sys.argv.insert(0, "-m")
try:
kwargs = {}
if follow_fork:
Expand All @@ -46,14 +43,20 @@ def _run_tracker(
raise MemrayCommandError(str(error), exit_code=1)

with tracker:
sys.argv[1:] = args.script_args
pid = os.getpid()
try:
if args.run_as_module:
sys.path[0] = os.getcwd()
# run_module will replace argv[0] with the script's path
sys.argv = ["", *args.script_args]
runpy.run_module(args.script, run_name="__main__", alter_sys=True)
elif args.run_as_cmd:
sys.path[0] = ""
sys.argv = ["-c", *args.script_args]
exec(args.script, {"__name__": "__main__"})
else:
sys.path[0] = str(pathlib.Path(args.script).resolve().parent.absolute())
sys.argv = [args.script, *args.script_args]
runpy.run_path(args.script, run_name="__main__")
finally:
if not args.quiet and post_run_message is not None and pid == os.getpid():
Expand Down

0 comments on commit fb510a2

Please sign in to comment.