Getting unexpected sys.argv when running script as a module

76 Views Asked by At

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)
1

There are 1 best solutions below

0
blhsing On

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.cmdline method in the cross-platform library psutil:

import psutil
print(psutil.Process().cmdline())

If you run the script above as python -mtest, it would output:

['/path/to/python', '-mtest']