python - 批处理文件使用 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
.
问题很明显,但我不知道如何解决这个问题。
解决方案
您可以使用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}")
推荐阅读
- c# - 过滤组成员 Graph API
- java - 如何配置 Spring 应用程序以在应用程序引擎上运行?
- python - 使用 ARIMA 模型来适应检测异常的阈值
- amazon-web-services - 用于修改 AWS HTTP 网关 HTTP_PROXY 集成中的标头的 Terraform 配置给出错误“指定的映射表达式无效”
- typescript - 在 TypeScript 中如何声明类方法的同义词?
- php - 如何修复 Stripe InvalidRequest 异常 - 无效数组异常?(PHP)
- python - 不使用 Numpy 打印 Checkboard
- python - 具有稀疏矩阵的 Numpy 'fromfunction'
- mysql - 通过基于产品 ID 的销售价格获得最后一次购买价格的利润,销售日期
- android - 您如何编写仅在字符串末尾删除 .0 的正则表达式字符串?