吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1092|回复: 18
上一主题 下一主题
收起左侧

[Python 原创] .bat/.vbs转.exe工具

  [复制链接]
跳转到指定楼层
楼主
cxr666 发表于 2025-6-23 18:42 回帖奖励
本帖最后由 苏紫方璇 于 2025-7-1 10:56 编辑

源代码供大家使用!



[Python] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import os
import sys
import subprocess
import argparse
from tkinter import Tk, filedialog, messagebox
import tempfile
import shutil
 
def convert_to_exe(input_file, output_file=None, icon=None, onefile=True, windowed=True):
    """
    将 .bat 或 .vbs 文件转换为 .exe 文件
    
    参数:
    input_file (str): 输入的 .bat 或 .vbs 文件路径
    output_file (str, optional): 输出的 .exe 文件路径,默认为输入文件名但扩展名为 .exe
    icon (str, optional): 可执行文件的图标路径
    onefile (bool, optional): 是否打包为单个文件
    windowed (bool, optional): 是否不显示控制台窗口
    """
    # 检查输入文件是否存在
    if not os.path.exists(input_file):
        print(f"错误: 文件 '{input_file}' 不存在")
        return False
    
    # 确定文件类型
    file_ext = os.path.splitext(input_file)[1].lower()
    if file_ext not in ['.bat', '.vbs']:
        print(f"错误: 不支持的文件类型 '{file_ext}',仅支持 .bat 和 .vbs 文件")
        return False
    
    # 确定输出文件名
    if output_file is None:
        output_file = os.path.splitext(input_file)[0] + '.exe'
    
    # 创建临时目录
    temp_dir = tempfile.mkdtemp()
    try:
        # 创建包装脚本
        wrapper_file = os.path.join(temp_dir, 'wrapper.py')
        with open(wrapper_file, 'w', encoding='utf-8') as f:
            f.write(f'''
import subprocess
import sys
import os
 
# 获取当前脚本所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))
 
# 构建要执行的脚本路径
bat_file = os.path.join(script_dir, '{os.path.basename(input_file)}')
 
# 复制原始脚本到临时目录
import shutil
shutil.copy2('{input_file}', bat_file)
 
# 执行脚本
if '{file_ext}' == '.bat':
    result = subprocess.run([bat_file], shell=True, capture_output=True, text=True)
else:
    result = subprocess.run(['cscript', bat_file], capture_output=True, text=True)
 
# 输出结果(如果不是windowed模式)
if not {windowed}:
    print("执行结果:")
    print(result.stdout)
    print(result.stderr)
 
# 如果需要返回退出码,可以使用 sys.exit(result.returncode)
sys.exit(0)
''')
         
        # 复制原始脚本到临时目录
        shutil.copy2(input_file, os.path.join(temp_dir, os.path.basename(input_file)))
         
        # 构建 PyInstaller 命令
        cmd = ['pyinstaller', '--clean']
         
        if onefile:
            cmd.append('--onefile')
         
        if windowed:
            cmd.append('--windowed')
         
        if icon and os.path.exists(icon):
            cmd.extend(['--icon', icon])
         
        cmd.extend(['--name', os.path.splitext(os.path.basename(output_file))[0]])
        cmd.extend(['--distpath', os.path.dirname(output_file)])
        cmd.extend(['--workpath', os.path.join(temp_dir, 'build')])
        cmd.append(wrapper_file)
         
        # 执行 PyInstaller 命令
        print("正在转换文件...")
        result = subprocess.run(cmd, capture_output=True, text=True)
         
        if result.returncode != 0:
            print(f"错误: PyInstaller 执行失败")
            print(result.stderr)
            return False
         
        print(f"转换成功! 输出文件: {output_file}")
        return True
    
    finally:
        # 清理临时目录
        shutil.rmtree(temp_dir, ignore_errors=True)
 
def main():
    """主函数,处理命令行参数和GUI交互"""
    parser = argparse.ArgumentParser(description='将 .bat 或 .vbs 文件转换为 .exe 文件')
    parser.add_argument('input_file', nargs='?', help='输入的 .bat 或 .vbs 文件路径')
    parser.add_argument('-o', '--output', help='输出的 .exe 文件路径')
    parser.add_argument('-i', '--icon', help='可执行文件的图标路径 (.ico)')
    parser.add_argument('--multi-file', action='store_true', help='打包为多个文件而不是单个文件')
    parser.add_argument('--console', action='store_true', help='显示控制台窗口')
    parser.add_argument('--gui', action='store_true', help='使用图形界面')
    
    args = parser.parse_args()
    
    # 如果指定了GUI模式或没有提供命令行参数,则使用GUI
    if args.gui or not args.input_file:
        root = Tk()
        root.withdraw()  # 隐藏主窗口
         
        input_file = filedialog.askopenfilename(
            title="选择 .bat 或 .vbs 文件",
            filetypes=[("批处理文件", "*.bat"), ("VBS文件", "*.vbs"), ("所有文件", "*.*")]
        )
         
        if not input_file:
            messagebox.showinfo("信息", "未选择文件,程序退出")
            return
         
        output_file = filedialog.asksaveasfilename(
            title="保存为 .exe 文件",
            defaultextension=".exe",
            filetypes=[("可执行文件", "*.exe"), ("所有文件", "*.*")]
        )
         
        if not output_file:
            messagebox.showinfo("信息", "未指定输出文件,程序退出")
            return
         
        icon_file = filedialog.askopenfilename(
            title="选择图标文件 (可选)",
            filetypes=[("图标文件", "*.ico"), ("所有文件", "*.*")]
        )
         
        onefile = not messagebox.askyesno("选项", "是否打包为多个文件?")
        windowed = not messagebox.askyesno("选项", "是否显示控制台窗口?")
         
        if icon_file:
            icon = icon_file
        else:
            icon = None
         
        success = convert_to_exe(
            input_file=input_file,
            output_file=output_file,
            icon=icon,
            onefile=onefile,
            windowed=windowed
        )
         
        if success:
            messagebox.showinfo("成功", f"文件已成功转换为: {output_file}")
        else:
            messagebox.showerror("错误", "文件转换失败")
             
    else:
        # 使用命令行参数
        convert_to_exe(
            input_file=args.input_file,
            output_file=args.output,
            icon=args.icon,
            onefile=not args.multi_file,
            windowed=not args.console
        )
 
if __name__ == "__main__":
    main()










下载:https://wwcq.lanzouu.com/i7s9D2zdtqef 无密码,感谢支持。

免费评分

参与人数 6吾爱币 +9 热心值 +6 收起 理由
galass + 1 + 1 厉害👍🏻
群重坤天 + 1 + 1 谢谢@Thanks!
苏紫方璇 + 5 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
schoolclub + 1 + 1 我很赞同!
9324 + 1 热心回复!
third1979 + 1 + 1 谢谢@Thanks!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

推荐
DrCatcher 发表于 2025-6-24 06:59
[Python] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import os
import sys
import subprocess
import argparse
from tkinter import Tk, filedialog, messagebox
import tempfile
import shutil
 
def convert_to_exe(input_file, output_file=None, icon=None, onefile=True, windowed=True):
    """
    将 .bat 或 .vbs 文件转换为 .exe 文件
    
    参数:
    input_file (str): 输入的 .bat 或 .vbs 文件路径
    output_file (str, optional): 输出的 .exe 文件路径,默认为输入文件名但扩展名为 .exe
    icon (str, optional): 可执行文件的图标路径
    onefile (bool, optional): 是否打包为单个文件
    windowed (bool, optional): 是否不显示控制台窗口
    """
    # 检查输入文件是否存在
    if not os.path.exists(input_file):
        print(f"错误: 文件 '{input_file}' 不存在")
        return False
    
    # 确定文件类型
    file_ext = os.path.splitext(input_file)[1].lower()
    if file_ext not in ['.bat', '.vbs']:
        print(f"错误: 不支持的文件类型 '{file_ext}',仅支持 .bat 和 .vbs 文件")
        return False
    
    # 确定输出文件名
    if output_file is None:
        output_file = os.path.splitext(input_file)[0] + '.exe'
    
    # 创建临时目录
    temp_dir = tempfile.mkdtemp()
    try:
        # 创建包装脚本
        wrapper_file = os.path.join(temp_dir, 'wrapper.py')
        with open(wrapper_file, 'w', encoding='utf-8') as f:
            f.write(f'''
import subprocess
import sys
import os
 
# 获取当前脚本所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))
 
# 构建要执行的脚本路径
bat_file = os.path.join(script_dir, '{os.path.basename(input_file)}')
 
# 复制原始脚本到临时目录
import shutil
shutil.copy2('{input_file}', bat_file)
 
# 执行脚本
if '{file_ext}' == '.bat':
    result = subprocess.run([bat_file], shell=True, capture_output=True, text=True)
else:
    result = subprocess.run(['cscript', bat_file], capture_output=True, text=True)
 
# 输出结果(如果不是windowed模式)
if not {windowed}:
    print("执行结果:")
    print(result.stdout)
    print(result.stderr)
 
# 如果需要返回退出码,可以使用 sys.exit(result.returncode)
sys.exit(0)
''')
         
        # 复制原始脚本到临时目录
        shutil.copy2(input_file, os.path.join(temp_dir, os.path.basename(input_file)))
         
        # 构建 PyInstaller 命令
        cmd = ['pyinstaller', '--clean']
         
        if onefile:
            cmd.append('--onefile')
         
        if windowed:
            cmd.append('--windowed')
         
        if icon and os.path.exists(icon):
            cmd.extend(['--icon', icon])
         
        cmd.extend(['--name', os.path.splitext(os.path.basename(output_file))[0]])
        cmd.extend(['--distpath', os.path.dirname(output_file)])
        cmd.extend(['--workpath', os.path.join(temp_dir, 'build')])
        cmd.append(wrapper_file)
         
        # 执行 PyInstaller 命令
        print("正在转换文件...")
        result = subprocess.run(cmd, capture_output=True, text=True)
         
        if result.returncode != 0:
            print(f"错误: PyInstaller 执行失败")
            print(result.stderr)
            return False
         
        print(f"转换成功! 输出文件: {output_file}")
        return True
    
    finally:
        # 清理临时目录
        shutil.rmtree(temp_dir, ignore_errors=True)
 
def main():
    """主函数,处理命令行参数和GUI交互"""
    parser = argparse.ArgumentParser(description='将 .bat 或 .vbs 文件转换为 .exe 文件')
    parser.add_argument('input_file', nargs='?', help='输入的 .bat 或 .vbs 文件路径')
    parser.add_argument('-o', '--output', help='输出的 .exe 文件路径')
    parser.add_argument('-i', '--icon', help='可执行文件的图标路径 (.ico)')
    parser.add_argument('--multi-file', action='store_true', help='打包为多个文件而不是单个文件')
    parser.add_argument('--console', action='store_true', help='显示控制台窗口')
    parser.add_argument('--gui', action='store_true', help='使用图形界面')
    
    args = parser.parse_args()
    
    # 如果指定了GUI模式或没有提供命令行参数,则使用GUI
    if args.gui or not args.input_file:
        root = Tk()
        root.withdraw()  # 隐藏主窗口
         
        input_file = filedialog.askopenfilename(
            title="选择 .bat 或 .vbs 文件",
            filetypes=[("批处理文件", "*.bat"), ("VBS文件", "*.vbs"), ("所有文件", "*.*")]
        )
         
        if not input_file:
            messagebox.showinfo("信息", "未选择文件,程序退出")
            return
         
        output_file = filedialog.asksaveasfilename(
            title="保存为 .exe 文件",
            defaultextension=".exe",
            filetypes=[("可执行文件", "*.exe"), ("所有文件", "*.*")]
        )
         
        if not output_file:
            messagebox.showinfo("信息", "未指定输出文件,程序退出")
            return
         
        icon_file = filedialog.askopenfilename(
            title="选择图标文件 (可选)",
            filetypes=[("图标文件", "*.ico"), ("所有文件", "*.*")]
        )
         
        onefile = not messagebox.askyesno("选项", "是否打包为多个文件?")
        windowed = not messagebox.askyesno("选项", "是否显示控制台窗口?")
         
        if icon_file:
            icon = icon_file
        else:
            icon = None
         
        success = convert_to_exe(
            input_file=input_file,
            output_file=output_file,
            icon=icon,
            onefile=onefile,
            windowed=windowed
        )
         
        if success:
            messagebox.showinfo("成功", f"文件已成功转换为: {output_file}")
        else:
            messagebox.showerror("错误", "文件转换失败")
             
    else:
        # 使用命令行参数
        convert_to_exe(
            input_file=args.input_file,
            output_file=args.output,
            icon=args.icon,
            onefile=not args.multi_file,
            windowed=not args.console
        )
 
if __name__ == "__main__":
    main()


看着难受,给你用代码块包裹了一下

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
ipc2008 + 1 + 1 谢谢@Thanks!

查看全部评分

3#
scbzwv 发表于 2025-6-23 22:25
4#
qqy123 发表于 2025-6-23 22:29
666,现在才知道bat批量处理脚本可以转exe可执行文件。
5#
kenkenss 发表于 2025-6-24 08:08
bat转exe是为了什么呢?不让人看bat里的命令。
6#
rayzju 发表于 2025-6-24 08:12
kenkenss 发表于 2025-6-24 08:08
bat转exe是为了什么呢?不让人看bat里的命令。

哈哈哈哈,感觉是有点那个。。。自己写点bat,也是为了调试方便,转来转去略微有点麻烦,除非是不希望别人改动
7#
LuckyClover 发表于 2025-6-24 08:25
有几个软件好像是可以bat转exe,试试楼主这个
8#
third1979 发表于 2025-6-24 08:36
原来bat批量处理脚本可以转exe可执行文件,谢谢分享
9#
云的彼岸918 发表于 2025-6-24 08:39
正在用的bat转换过去打开没有任何显示
10#
wqdcs 发表于 2025-6-24 08:46
有点好奇bat转EXE后执行,是啥界面?
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-7-29 10:09

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表