test.py:
import sys
print(sys.executable, [sys.executable] + sys.argv)
Running normally:
C:\Program Files\Python\Python311\python.exe ['C:\\Program Files\\Python\\Python311\\python.exe', 'test.py']
Running as a module:
C:\Program Files\Python\Python311\python.exe ['C:\\Program Files\\Python\\Python311\\python.exe', 'C:\\Users\\susha\\Documents\\Test\\test.py']
Expectation:
C:\Program Files\Python\Python311\python.exe ['C:\\Program Files\\Python\\Python311\\python.exe', '-m', 'test']
How I am going to use it:
for path, _, files in os.walk("."):
for file in files:
if file.endswith(".py") and os.path.getmtime(os.path.join(path, file)) > self.init_time:
print(file, os.path.getmtime(os.path.join(path, file)), os.path.getmtime(__file__))
self.logger.info("File<%s> changed. Reloading..." % file)
print(sys.executable, [sys.executable] + sys.argv)
os.execv(sys.executable, sys.argv)
The original command line used to run a Python script is not exposed by the Python API, but can be obtained from a platform-dependent system call, which, conveniently, has been written as the
Process.cmdlinemethod in the cross-platform librarypsutil:If you run the script above as
python -mtest, it would output: