使用os.execute执行copy命令时提示找不到文件的问题求助
Lua中os.execute执行copy命令报错的问题排查与解决
问题背景
使用Lua的os.execute调用copy命令复制文件时,持续收到提示The system cannot find the file specified.,但在CMD提示符中手动执行相同命令可正常复制。测试代码能运行,但封装后的函数块无法正常执行,尝试用cd切换目录也无效。
错误原因分析
os.execute的子进程独立性:每个os.execute调用都会启动独立的CMD子进程,cd命令仅对当前子进程生效,后续的os.execute仍会回到Lua程序的初始工作目录,切换目录操作无效。- 目标文件名末尾多余空格:变量
State_Json_Backup的末尾多了一个空格,导致copy命令解析目标路径时出错,且未用引号包裹带空格的路径,CMD无法识别。 copy命令格式错误:源路径和目标路径之间没有空格分隔,CMD无法正确解析命令参数。
修复方案
针对上述问题,修改后的代码如下:
local function Backup_JSON () local TURN_NO = "03" -- 用字符串避免数字自动转义(如03会被解析为3) local Current_Date = os.date("%m-%d-%Y") local Current_Time_02 = os.date("%H_%M_%S") if not Current_Time_02 then print("\n\nOS not accessible\n") return end print("\n\nIn else statement to copy state file\n") -- 移除目标文件名末尾的多余空格 local State_Json_Backup = "C:\\Users\\AKA_Liberation\\Saved Games\\dcs_liberation\\state_T" .. TURN_NO .. "_" .. Current_Date .. "_" .. Current_Time_02 .. ".json" -- 方案1:将cd和copy放在同一个子进程执行(用&&连接命令) local Backup, err_02 = os.execute("cd C:\\Users\\AKA_Liberation\\Saved Games\\dcs_liberation && copy state.json \"" .. State_Json_Backup .. "\"") -- 方案2:直接使用完整路径,无需切换目录(更可靠) -- local Backup, err_02 = os.execute("copy \"C:\\Users\\AKA_Liberation\\Saved Games\\dcs_liberation\\state.json\" \"" .. State_Json_Backup .. "\"") if err_02 then print("\n\n" .. err_02 .. "\n") end end Backup_JSON()
更优替代方案:使用Lua原生文件API
避免依赖CMD命令,直接用Lua的io库进行文件复制,兼容性更好且更可控:
-- 通用文件复制函数 local function copy_file(source_path, dest_path) local src_handle = io.open(source_path, "rb") if not src_handle then return false, "无法打开源文件:" .. source_path end local dest_handle = io.open(dest_path, "wb") if not dest_handle then src_handle:close() return false, "无法创建目标文件:" .. dest_path end -- 读取源文件所有内容并写入目标文件 dest_handle:write(src_handle:read("*a")) -- 关闭文件句柄 src_handle:close() dest_handle:close() return true end local function Backup_JSON () local TURN_NO = "03" local Current_Date = os.date("%m-%d-%Y") local Current_Time_02 = os.date("%H_%M_%S") if not Current_Time_02 then print("\n\nOS not accessible\n") return end print("\n\nIn else statement to copy state file\n") local source_file = "C:\\Users\\AKA_Liberation\\Saved Games\\dcs_liberation\\state.json" local dest_file = "C:\\Users\\AKA_Liberation\\Saved Games\\dcs_liberation\\state_T" .. TURN_NO .. "_" .. Current_Date .. "_" .. Current_Time_02 .. ".json" local success, err_msg = copy_file(source_file, dest_file) if not success then print("\n\n复制失败:" .. err_msg .. "\n") end end Backup_JSON()
内容的提问来源于stack exchange,提问作者Nathan C.
相关产品推荐
相关产品推荐

