You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell/CMD命令中读取文件内的版本号作为参数

从文件读取版本号并自动传入命令参数

我需要在PowerShell/CMD的命令参数中自动填入存储在文件里的版本号。比如有这样一条命令:

py -m non_important_script --file-version={从文件获取的值}

版本号存放在version.py文件中,文件只有一行内容:

__version__ = "1.2.0"

我不想每次手动更新参数,希望命令能自动读取版本号。试了下面这条命令但执行失败:

py -m non_important_script --file-version=(Select-String -Path .\version.py -Pattern "\d.\d.\d").Matches.Groups[0].value

脚本返回错误:

FATAL:
Error, specify only one positional argument unless "--run" is specified to
pass them to the compiled program execution.


问题原因

你用了普通括号()包裹PowerShell子表达式,但PowerShell中必须用**子表达式运算符$()**才能正确将命令输出结果作为单个参数值传递。直接用()会被解析成多个位置参数,触发脚本的参数错误。

正确的PowerShell命令

py -m non_important_script --file-version=$((Select-String -Path .\version.py -Pattern "\d+\.\d+\.\d+").Matches.Groups[0].Value)

同时优化了正则表达式:把\d.\d.\d改为\d+\.\d+\.\d+,这样能匹配多位数的版本号(比如1.10.3),用\.转义点号避免匹配任意字符。

更精准的写法(可选)

如果要确保只提取__version__行的版本号,避免文件中其他类似数字串干扰,可以用更精确的正则:

py -m non_important_script --file-version=$((Select-String -Path .\version.py -Pattern '__version__\s*=\s*"(\d+\.\d+\.\d+)"').Matches.Groups[1].Value)

这个正则会精准定位__version__ = "x.x.x"的行,直接提取引号内的版本号。

CMD下的实现(如果需要)

如果用CMD执行,可通过for /f命令提取版本号:

for /f tokens^=2^ delims^=^" %%v in (version.py) do py -m non_important_script --file-version=%%v

内容的提问来源于stack exchange,提问作者Sea Wolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 23:45:29