[英]Error when trying to start python.exe from C#
我正在嘗試從 C# 執行 python 腳本。 我在以下鏈接的另一篇文章中找到了一種方法來完成此操作: run a python script from c# 。 但是,當進程到達 using (Process process = Process.Start(start))
行時,我收到錯誤消息。 這是我正在實施的代碼:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RunPy
{
class Program
{
static void Main(string[] args)
{
// As an example, cmd would be @C:/Python26/python.exe and args would be C://Python26//test.py 100
String cmd = "@C:/Program Files (x86)/Python27/python.exe";
String argss = "C:/My_Python_lib/happyBirthday.py 'joe'";
// Console.Write(argss); this line is just to test the output of the above argss
// Console.ReadLine(); this line goes with the above line to prevent the window from closing so fast
run_cmd(cmd, argss);
//ProcessStartInfo startInfo = new ProcessStartInfo();
//startInfo.FileName = cmd;
//Process.Start(cmd);
}
private static void run_cmd(string cmd, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = cmd;
start.Arguments = args;
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
}
}
}
這是我回來的錯誤:
System.dll 中發生類型為“System.ComponentModel.Win32Exception”的未處理異常
任何幫助將不勝感激。 謝謝!
您錯誤地初始化了cmd
變量。 "@" 應該在引號之前(即@"C:/...")。 當然,使用正斜杠而不是反斜杠無論如何都不需要逐字字符串,因此您可以完全省略“@”。
String cmd = "C:/Program Files (x86)/Python27/python.exe";
試試看
string cmd = @"C:\Program Files (x86)\Python27\python.exe";
或
string cmd = @"C:\PROGRA~1\Python27\python.exe";
首先讀取python exe並將其加載到內存中。
var assembly = Assembly.GetExecutingAssembly();
var resourcePath = assembly.GetManifestResourceNames().Single(str => str.EndsWith("python.exe"));
FileStream outputFileStream = new FileStream(Path.Combine(Directory.GetCurrentDirectory(), resourcePath), FileMode.OpenOrCreate, FileAccess.ReadWrite);
using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
{
if (stream != null)
{
stream.CopyTo(outputFileStream);
stream.Close();
}
outputFileStream.Close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.