批处理文件使用 sys.argv[] 执行 Python 脚本
Batch file executes Python script with sys.argv[]
我为执行 python 脚本的 windows 终端创建了自定义命令 scan
。
@echo off
python "my_scripts\scan.py"
为了初步测试,我编写了这个很棒的脚本。
import sys
print(f"The name of the script is: { sys.argv[0] }")
当我在 shell 中键入 scan
时,据我所知,这应该只是打印:The name of the script is: scan
.
但是,我得到的输出是:The name of the script is: my_scripts\scan.py
。
问题很明显,但我不知道如何解决。
您可以使用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}")
我为执行 python 脚本的 windows 终端创建了自定义命令 scan
。
@echo off
python "my_scripts\scan.py"
为了初步测试,我编写了这个很棒的脚本。
import sys
print(f"The name of the script is: { sys.argv[0] }")
当我在 shell 中键入 scan
时,据我所知,这应该只是打印:The name of the script is: scan
.
但是,我得到的输出是:The name of the script is: my_scripts\scan.py
。
问题很明显,但我不知道如何解决。
您可以使用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}")