首页 > 解决方案 > 批处理文件使用 sys.argv[] 执行 Python 脚本

问题描述

scan我为执行 python 脚本的 windows 终端创建了一个自定义命令。

@echo off
python "my_scripts\scan.py"

对于初始测试,我编写了这个绝妙的脚本。

import sys

print(f"The name of the script is: { sys.argv[0] }")

据我所知,当我scan在 shell 中输入时,这应该只是打印:The name of the script is: scan

但相反,我得到的输出是:The name of the script is: my_scripts\scan.py.

问题很明显,但我不知道如何解决这个问题。

标签: pythonbatch-filesys

解决方案


您可以使用Path.stem来获取不带扩展名的文件名

__file__是您可以传递到的当前文件的完整路径Path

from pathlib import Path

print(f"The name of the script is: {Path(__file__).stem}")

sys.argv[0]如果你愿意,你也可以通过

from pathlib import Path
import sys

print(f"The name of the script is: {Path(sys.argv[0]).stem}")

推荐阅读