首页 > 解决方案 > 我正在尝试通过从 c# 调用 python 来通过 python 执行批处理文件。仅使用python脚本单独触发批处理文件不执行

问题描述

  1. C# 程序的 Python 触发器工作正常。
  2. 仅来自 Python 的批处理脚本不起作用。

我正在尝试通过从 C# 调用 Python 来通过 Python 执行批处理文件。当我们通过 MVC 应用程序运行时,仅使用 Python 脚本的批处理文件触发器不会执行
,但当 Python 脚本直接运行时它可以正常工作。

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "C:/Program Files/Python 3.5/python.exe";
//startInfo.Arguments = "C:/inetpub/wwwroot/MATS_BAT_Script/Python_Scripts/MATSUpgrade.py";
startInfo.Arguments = HttpContext.Server.MapPath("~/Python_Scripts/MATSUpgrade.py").ToString();

startInfo.Verb = "runas";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
process.StartInfo = startInfo;
bool t = process.Start();

System.IO.StreamReader myStreamReader = process.StandardError;
string error = myStreamReader.ReadToEnd();
string test = error;
System.IO.StreamReader reader = process.StandardOutput;
string output = reader.ReadToEnd();

process.WaitForExit();

process.Close();

Python:

try:
    writerMATS.save()
    subprocess.run(['C:\inetpub\wwwroot\MATS_History_Load_App\Python_Scripts\Copy_Batch_Trigger.bat'], shell = True, check = True, capture_output = True)
except Exception:
    print(Exception)

批处理脚本:

COPY / Y C: \inetpub\wwwroot\MATS_History_Load_App\Python_Scripts\MATSUpgrade.xlsx\servewr ip\Mats\Mats_Test\MATSUpgrade.xlsx

标签: c#python-3.xbatch-filemodel-view-controller

解决方案


您不能直接运行批处理文件。您必须调用 cmd.exe 为您解释批处理文件,例如:

cmd.exe /c C:\inetpub\wwwroot\MATS_History_Load_App\Python_Scripts\Copy_Batch_Trigger.bat


推荐阅读