将脚本作为模块运行时出现意外的 sys.argv

问题描述 投票:0回答:1

测试.py:

import sys

print(sys.executable, [sys.executable] + sys.argv)

正常运行:

C:\Program Files\Python\Python311\python.exe ['C:\\Program Files\\Python\\Python311\\python.exe', 'test.py']

作为模块运行:

C:\Program Files\Python\Python311\python.exe ['C:\\Program Files\\Python\\Python311\\python.exe', 'C:\\Users\\susha\\Documents\\Test\\test.py']

期望:

C:\Program Files\Python\Python311\python.exe ['C:\\Program Files\\Python\\Python311\\python.exe', '-m', 'test']

我将如何使用它:

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)
python sys
1个回答
0
投票

用于运行 Python 脚本的原始命令行不是由 Python API 公开的,而是可以从依赖于平台的系统调用中获取,为了方便起见,该系统调用已被编写为跨平台中的

Process.cmdline
方法。平台库
psutil
:

import psutil
print(psutil.Process().cmdline())
© www.soinside.com 2019 - 2024. All rights reserved.