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();

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

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

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.

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?

Thanks in advance,

解决方案

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

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);

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).

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.

Edit

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值