从C#执行Python脚本 [英] Executing Python Script from C#

查看:276
本文介绍了从C#执行Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过以下方式执行从C#中的python脚本:

I am trying to execute the python script from C# in the following way:

int ExitCode;
ProcessStartInfo ProcessInfo;
Process Process;

ProcessInfo = new ProcessStartInfo();
ProcessInfo.FileName = "C:\Python27\python.exe";
ProcessInfo.Arguments = "C:\generate.py book1.pdf";
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = false;
ProcessInfo.RedirectStandardOutput = true;

Process = Process.Start(ProcessInfo);
Process.WaitForExit();
ExitCode = Process.ExitCode;
Process.Close();

当我执行此服务器上,我得到的ExitCode为1。但是,同样的代码工作细本地。

When I execute this on the server, I get the ExitCode as 1. But the same code is working fine locally.

此外,当我从运行此命令的命令提示符,Python脚本的执行没有任何问题。

Also when I run this command from the cmd prompt, the python script executes without any issues.

本Python脚本实际上是被用来转换的PDF页面的SWF文件,提取网页上的文字,并使用各种开放源PDG页面的缩略图。

This python script is actually being used to convert the PDF pages to SWF files, extract the text from pages and create thumbnail of the pdg pages using various open sources.

提前任何人都可以请帮助我理解这可能是上面的C#代码的问题,或者我需要在服务器上设置任何权限?

Can anyone please help me understand what could be the issue with above C# code or do I need to set any permissions on the server?

谢谢,

推荐答案

从的这里错误代码2代表 ERROR_FILE_NOT_FOUND ,所以你应该有一些问题的路径/ 。文件权限

From here error code 2 stands for ERROR_FILE_NOT_FOUND, so you should have some problem with the path/file permissions.

首先,你可以只读取从Python过程中的输出和错误,看看你从那里得到一些信息:

First of all you can just read the stdout and stderr from the python process and see if you get some information from there:

    ProcessInfo.RedirectStandardOutput = true;
    ProcessInfo.RedirectStandardError = true;
    // (...)
    Process.WaitForExit();
    string stderr = Process.StandardError.ReadToEnd();
    string stdout = Process.StandardOutput.ReadToEnd();
    Console.WriteLine("STDERR: " + stderr);
    Console.WriteLine("STDOUT: " + stdout);



大概的WriteLine是不是呈现信息的最佳方式,因此与之相适应,以更好地满足您的需求(日志信息,写在一个临时文件等等)。

Probably WriteLine is not the best way to present the information, so adapt it to better suit your needs (log that information, write it on a temp file, etc).

此外,我几乎不知道如何在C#程序,但是当我试着写类似你们的节目因为路径没有逃脱它给了我一个错误。所以,你也可以尝试用\\更换\:

Also I barely know how to program in C#, but when I tried to write a program similar to yours it gave me an error because paths were not escaped. So you can also try to replace \ with \\:

ProcessInfo.FileName = "C:\\Python27\\python.exe";
ProcessInfo.Arguments = "C:\\generate.py book1.pdf";



祝你好运。

Good luck.

我只注意到我(1)与他人的评论(2),但这些技巧仍然可以帮助你迷惑你的错误代码。

I just noticed I confused your error code(1) with others on the comments(2),but those tips may still help you.

这篇关于从C#执行Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆