VS2022调用Python脚本报Errno 2错误的求助
问题:点击按钮运行Python脚本时抛出"Errno 2 no such file or directory"错误
在Visual Studio 2022中编写WinForms按钮点击事件,预期调用Python运行指定脚本,但反复核对路径(复制到文件资源管理器能正常找到对应文件)后仍出现该错误,代码如下:
private void button1_Click(object sender, EventArgs e) { try { string pythonPath = @"C:\Users\Dmitry\AppData\Local\Programs\Python\Python38-32\python.exe"; string scriptPath = @"C:\Users\Dmitry\Documents\Bots Python\Autoclicker.py"; if (!System.IO.File.Exists(pythonPath)) { MessageBox.Show($"Python executable not found: {pythonPath}"); return; } if (!System.IO.File.Exists(scriptPath)) { MessageBox.Show($"Python script not found: {scriptPath}"); return; } var startInfo = new System.Diagnostics.ProcessStartInfo { FileName = pythonPath, Arguments = scriptPath, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; using (var process = System.Diagnostics.Process.Start(startInfo)) { string output = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); process.WaitForExit(); if (!string.IsNullOrEmpty(output)) { MessageBox.Show($"Output: {output}"); } if (!string.IsNullOrEmpty(error)) { MessageBox.Show($"Error: {error}"); } } } catch (Exception ex) { MessageBox.Show($"Exception: {ex.Message}"); } }
解决方案
给含空格的脚本路径添加引号:你的脚本路径包含空格(
Bots Python文件夹),直接作为参数传递会被Python解析成两个独立参数,导致找不到目标脚本。修改Arguments赋值代码:Arguments = $"\"{scriptPath}\"",显式设置Python进程的工作目录:当
UseShellExecute = false时,进程默认工作目录是当前WinForms程序的执行目录,如果你的Python脚本依赖同目录下的其他文件,会导致找不到依赖。添加工作目录设置:var startInfo = new System.Diagnostics.ProcessStartInfo { FileName = pythonPath, Arguments = $"\"{scriptPath}\"", RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = System.IO.Path.GetDirectoryName(scriptPath) // 新增此行 };查看完整错误上下文:有时候错误提示的"no such file"并非指向脚本本身,而是脚本内部引用的文件。可以临时将
CreateNoWindow设为false,打开Python控制台查看完整错误;或者在Python脚本开头添加代码打印当前工作目录:import os print("当前工作目录:", os.getcwd())
内容的提问来源于stack exchange,提问作者someguywhocodes
相关产品推荐
相关产品推荐

