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

如何用Python提取指定行数字并除以1000,实现VBS Sleep转Python Sleep

实现VBScript Sleep到Python Sleep的转换

要完成WScript.sleep()到time.sleep()的转换,核心是提取括号内的毫秒数并转换为秒,直接字符串拼接无法处理动态数字,需用正则表达式匹配替换:

修正后的Python代码

import time
import re

def convert_vbs_sleep(vbs_code):
    # 定义匹配wscript.sleep(数字)的正则,捕获括号内的数字
    def replace_sleep(match):
        ms = int(match.group(1))
        sec = ms / 1000
        return f"time.sleep({sec})"
    
    # 全局替换所有符合条件的sleep语句(忽略大小写)
    return re.sub(r'wscript\.sleep\((\d+)\)', replace_sleep, vbs_code, flags=re.IGNORECASE)

# 读取VBS文件并执行转换
with open("test.vbs", "r") as f:
    vbs_data = f.read()

converted_code = convert_vbs_sleep(vbs_data)
# 可将转换后的代码保存或直接执行
print(converted_code)

关键说明

  • 正则r'wscript\.sleep\((\d+)\)':精准匹配wscript.sleep(数字)格式,括号内的数字会被捕获为分组1,同时通过flags=re.IGNORECASE兼容大小写写法(比如WScript.Sleep)
  • 回调函数replace_sleep:将捕获的毫秒数转为整数,除以1000得到秒数,再拼接成Python的time.sleep()语句
  • 使用with语句读取文件:自动管理文件资源,避免遗漏关闭操作

测试效果

针对你的VBS代码:

msgbox("Hello!")
wscript.sleep(5000)
msgbox("This appears in 5 seconds!")

转换后会得到:

msgbox("Hello!")
time.sleep(5.0)
msgbox("This appears in 5 seconds!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:42:18