0

I need to run files using python -m foo.bar.baz due to having absolute imports in other areas of the codebase.

In VS Code, when I click the top-right corner to Run Python File, I'd like it to automatically do python -m foo.bar.baz instead of python /absolute/path/to/foo/bar/baz.py. Is this possible?

Of course, this should work automatically for any file regardless of where it is, not just for baz.py.

This question suggests modifying settings.json but they don't provide an explicit example for how to do it exactly like this.

codeananda
  • 939
  • 1
  • 10
  • 16
  • try this https://stackoverflow.com/questions/52786022/shortcut-for-running-terminal-command-in-vs-code – Sergio2405 Mar 01 '23 at 13:54
  • @Sergio2405 that might be helpful but it's not a complete answer. How do I ensure is uses the correct path to the file separated by dots and not slashes? Is there a built-in variable for that? – codeananda Mar 01 '23 at 13:59
  • look at the options of the python launch config – rioV8 Mar 01 '23 at 15:58
  • @rioV8 I've tried that but couldn't figure it out. Could you post an answer filling in the correct info? – codeananda Mar 01 '23 at 16:26
  • 2
    This isn't possible in the general case: Whether `python -m` is available for a given piece of code depends on `sys.path` and where it is relative to any entries in same. Some .py files won't be located at a valid (`import`able) module location at all. One can try to heuristically guess, or set up a shim that adjusts PYTHONPATH, but getting that guess wrong will have messy side effects, so I don't advise the attempt. – Charles Duffy Mar 01 '23 at 18:17

1 Answers1

0

when I click the top-right corner to Run Python File, I'd like it to automatically do python -m foo.bar.baz instead of python /absolute/path/to/foo/bar/baz.py

I don't think this is possible at the time of this writing.

The settings relating to running the active Python file in the terminal start with python.terminal.. I don't see any such settings to get exactly what you want.

For the part of just passing arguments to the Python interpreter, use the "python.terminal.launchArgs": [] setting in your settings.json file and fill the array with commandline argument strings.

The setting's description:

Python launch arguments to use when executing a file in the terminal.

Ex.

python.terminal.launchArgs": ["-m"]
starball
  • 20,030
  • 7
  • 43
  • 238