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

双击运行Python脚本时Shutil无法复制文件,Shell中运行正常

问题分析与解决方案

核心问题

双击运行脚本时无响应,本质是输入不合法导致变量未定义或抛出异常,但因为窗口自动关闭,你看不到错误提示:

  • 若输入非整数(比如字母、空格),int(input())会直接抛出ValueError,脚本终止
  • 若输入1/2以外的数字,src变量未被赋值,执行shutil.copy2时会抛出NameError,脚本终止

修复后的代码

import shutil
import time

# 循环获取合法输入
while True:
    try:
        choice = int(input('''1. or  2. 
'''))
        if choice in (1, 2):
            break
        else:
            print("请输入1或2!")
    except ValueError:
        print("请输入有效数字!")

# 赋值源文件路径
if choice == 1:
    src = r'C:\directory\image.png'
    print("chosen 1!")
elif choice == 2:
    src = r'C:\different directory\image.png'
    print("chosen 2!")

dst = r'C:\directory\destination_image.png'
 
print("Trying to copy...")
try:
    shutil.copy2(src, dst)
    print("File copied successfully.")
except Exception as e:
    print(f"复制失败:{str(e)}")
time.sleep(5)  # 延长等待时间,确保能看到结果

额外优化建议

  • 用**原始字符串(r'路径')**避免转义字符出错
  • 给桌面快捷方式设置工作目录:右键快捷方式→属性→起始位置,填写脚本所在的绝对目录
  • 若想彻底避免窗口关闭问题,可把脚本打包成exe(用pyinstaller工具),或改用tkinter做简单图形界面输入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:30:59