By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,136 Members | 1,054 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,136 IT Pros & Developers. It's quick & easy.

starting some Python script from C#

P: n/a
Hello.

How can I run some Python script within C# program?

Thanks,

Zlatko
May 27 '06 #1
Share this Question
Share on Google+
6 Replies


P: n/a
tatamata wrote:
Hello.

How can I run some Python script within C# program?


---------------------------------------------------------------------------------
ProcessStartInfo startInfo;
Process process;
string directory;
string pyArgs;
string script;

startInfo = new ProcessStartInfo("python");
startInfo.WorkingDirectory = directory;
startInfo.Arguments = script + " " + pyArgs;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;

process = new Process();
process.StartInfo = startInfo;
process.Start();

string s;
while ((s = process.StandardOutput.ReadLine()) != null)
{
//do something with s
}
---------------------------------------------------------------------------------

HTH

Gerard

May 27 '06 #2

P: n/a
thanks.

"Gerard Flanagan" <gr********@yahoo.co.uk> je napisao u poruci interesnoj
grupi:11**********************@i39g2000cwa.googleg roups.com...
tatamata wrote:
Hello.

How can I run some Python script within C# program?


---------------------------------------------------------------------------------
ProcessStartInfo startInfo;
Process process;
string directory;
string pyArgs;
string script;

startInfo = new ProcessStartInfo("python");
startInfo.WorkingDirectory = directory;
startInfo.Arguments = script + " " + pyArgs;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;

process = new Process();
process.StartInfo = startInfo;
process.Start();

string s;
while ((s = process.StandardOutput.ReadLine()) != null)
{
//do something with s
}
---------------------------------------------------------------------------------

HTH

Gerard

May 27 '06 #3

P: n/a
Hello. I tried to implement ypour suggestion, but an error apears:
"Exception System.ComponentModel.Win32Exception was thrown in debugee:
The specified executable is not a valid Win32 application.

StartWithCreateProcess()
Start()
Start()
Main() - c:\Documents and Settings\Zlatko\My Documents\SharpDevelop
Projects\CS_script\CS_script\Main.cs:32,5 "

The C# code is the following:

/*
* Created by SharpDevelop.
* User: Zlatko
* Date: 28.5.2006
* Time: 9:38
*
* To change this template use Tools | Options | Coding | Edit Standard
Headers.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace CS_script
{
class MainClass
{
public static void Main(string[] args)
{

System.Diagnostics.ProcessStartInfo psi =new
System.Diagnostics.ProcessStartInfo();
psi.FileName="my_script.py";
psi.WorkingDirectory=Environment.CurrentDirectory;
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;

System.Diagnostics.Process script;
script = System.Diagnostics.Process.Start(psi);

System.IO.StreamReader myOutput = script.StandardOutput;
script.WaitForExit(2000);
if (script.HasExited)
{
string output = myOutput.ReadToEnd();
//this.processResults.Text = output;
}
MessageBox.Show("finished!");
}
}
}

When running the program, I have the following error:

"Exception System.ComponentModel.Win32Exception was thrown in debugee:
The specified executable is not a valid Win32 application.

StartWithCreateProcess()
Start()
Start()
Main() - c:\Documents and Settings\Zlatko\My Documents\SharpDevelop
Projects\CS_script\CS_script\Main.cs:32,5 "

"Gerard Flanagan" <gr********@yahoo.co.uk> je napisao u poruci interesnoj
grupi:11**********************@i39g2000cwa.googleg roups.com...
tatamata wrote:
Hello.

How can I run some Python script within C# program?


---------------------------------------------------------------------------------
ProcessStartInfo startInfo;
Process process;
string directory;
string pyArgs;
string script;

startInfo = new ProcessStartInfo("python");
startInfo.WorkingDirectory = directory;
startInfo.Arguments = script + " " + pyArgs;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;

process = new Process();
process.StartInfo = startInfo;
process.Start();

string s;
while ((s = process.StandardOutput.ReadLine()) != null)
{
//do something with s
}
---------------------------------------------------------------------------------

HTH

Gerard

May 28 '06 #4

P: n/a
> "Gerard Flanagan" <gr********@yahoo.co.uk> je napisao u poruci interesnoj
grupi:11**********************@i39g2000cwa.googleg roups.com...
tatamata wrote:
Hello.

How can I run some Python script within C# program?

---------------------------------------------------------------------------------
ProcessStartInfo startInfo;
Process process;
string directory;
string pyArgs;
string script;

startInfo = new ProcessStartInfo("python");
startInfo.WorkingDirectory = directory;
startInfo.Arguments = script + " " + pyArgs;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;

process = new Process();
process.StartInfo = startInfo;
process.Start();

string s;
while ((s = process.StandardOutput.ReadLine()) != null)
{
//do something with s
}
---------------------------------------------------------------------------------


tatamata wrote: Hello. I tried to implement ypour suggestion, but an error apears:
"Exception System.ComponentModel.Win32Exception was thrown in debugee:
The specified executable is not a valid Win32 application.

namespace CS_script
{
class MainClass
{
public static void Main(string[] args)
{

System.Diagnostics.ProcessStartInfo psi =new
System.Diagnostics.ProcessStartInfo();
psi.FileName="my_script.py";
psi.WorkingDirectory=Environment.CurrentDirectory;
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;

System.Diagnostics.Process script;
script = System.Diagnostics.Process.Start(psi);

System.IO.StreamReader myOutput = script.StandardOutput;
script.WaitForExit(2000);
if (script.HasExited)
{
string output = myOutput.ReadToEnd();
//this.processResults.Text = output;
}
MessageBox.Show("finished!");
}
}
}

When running the program, I have the following error:

"Exception System.ComponentModel.Win32Exception was thrown in debugee:
The specified executable is not a valid Win32 application.

StartWithCreateProcess()
Start()
Start()
Main() - c:\Documents and Settings\Zlatko\My Documents\SharpDevelop
Projects\CS_script\CS_script\Main.cs:32,5 "

I have no means of running C# programs at present and can't claim much
expertise in any case. A guess is that a "valid Win32 application"
means an '.exe' file, not a '.py' file.

You are assuming that a Process object is as smart as the command
interpreter ('cmd.exe') and will know to use 'python.exe' for a file
with a 'py' extension?

What happens if you use 'python.exe' (or 'cmd.exe') as your file and
the script name as argument as in the code I posted?

Gerard
(PS. This group prefers that one doesn't top-post)

May 28 '06 #5

P: n/a
Hello. It seems that the following code works. And it seems that Process
object can automatically run script by using python.exe, but only if
standard output is not redirected...

/*
* Created by SharpDevelop.
* User: Zlatko
* Date: 28.5.2006
* Time: 9:38
*
* To change this template use Tools | Options | Coding | Edit Standard
Headers.
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.ComponentModel;
using System.Windows.Forms;

namespace CS_script
{

class MainClass
{
public static void Main(string[] args)
{
MyProcess myProcess = new MyProcess();
myProcess.ExecuteScript();
MessageBox.Show("Continue?","Application",
MessageBoxButtons.OKCancel);
}
}
public class MyProcess
{
// These are the Win32 error code for file not found or access
denied.
const int ERROR_FILE_NOT_FOUND =2;
const int ERROR_ACCESS_DENIED = 5;

/// <summary>
/// Executes a python script.
/// </summary>
public void ExecuteScript()
{
Process myProcess = new Process();

try
{
// Get the path that stores the python script.
//string myDocumentsPath
=Environment.GetFolderPath(Environment.SpecialFold er.Personal);
//If the script is placed in the same folder as C#
executable, set the path to current directory:
string myDocumentsPath=Environment.CurrentDirectory;

//Set the fully qualified script name
myProcess.StartInfo.FileName = myDocumentsPath +
"\\my_script.py";

//Execute the script:
myProcess.Start();

//string output = myProcess.StandardOutput.ReadToEnd();
//Console.WriteLine(output);

//Console.WriteLine(myProcess.StandardOutput.ReadToE nd());

//TextReader t = myProcess.StandardOutput;
//MessageBox.Show(t.ReadToEnd());

// Wait for it to die...
myProcess.WaitForExit();

MessageBox.Show ("Python script is successfully executed!");

}
catch (Win32Exception e)
{
if(e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
{
Console.WriteLine(e.Message + ". Check the path.");
}

else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
{
// Note that if your word processor might generate
exceptions
// such as this, which are handled first.
Console.WriteLine(e.Message +
". You do not have permission to print this file.");
}
}
}
}
}

Greetings,

Zlatko

"Gerard Flanagan" <gr********@yahoo.co.uk> je napisao u poruci interesnoj
grupi:11*********************@j73g2000cwa.googlegr oups.com...
"Gerard Flanagan" <gr********@yahoo.co.uk> je napisao u poruci interesnoj
grupi:11**********************@i39g2000cwa.googleg roups.com...
> tatamata wrote:
>> Hello.
>>
>> How can I run some Python script within C# program?
>>
>
> ---------------------------------------------------------------------------------
> ProcessStartInfo startInfo;
> Process process;
> string directory;
> string pyArgs;
> string script;
>
> startInfo = new ProcessStartInfo("python");
> startInfo.WorkingDirectory = directory;
> startInfo.Arguments = script + " " + pyArgs;
> startInfo.UseShellExecute = false;
> startInfo.CreateNoWindow = true;
> startInfo.RedirectStandardOutput = true;
> startInfo.RedirectStandardError = true;
>
> process = new Process();
> process.StartInfo = startInfo;
> process.Start();
>
> string s;
> while ((s = process.StandardOutput.ReadLine()) != null)
> {
> //do something with s
> }
> ---------------------------------------------------------------------------------
>


tatamata wrote:
Hello. I tried to implement ypour suggestion, but an error apears:
"Exception System.ComponentModel.Win32Exception was thrown in debugee:
The specified executable is not a valid Win32 application.

namespace CS_script
{
class MainClass
{
public static void Main(string[] args)
{

System.Diagnostics.ProcessStartInfo psi =new
System.Diagnostics.ProcessStartInfo();
psi.FileName="my_script.py";
psi.WorkingDirectory=Environment.CurrentDirectory;
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;

System.Diagnostics.Process script;
script = System.Diagnostics.Process.Start(psi);

System.IO.StreamReader myOutput = script.StandardOutput;
script.WaitForExit(2000);
if (script.HasExited)
{
string output = myOutput.ReadToEnd();
//this.processResults.Text = output;
}
MessageBox.Show("finished!");
}
}
}

When running the program, I have the following error:

"Exception System.ComponentModel.Win32Exception was thrown in debugee:
The specified executable is not a valid Win32 application.

StartWithCreateProcess()
Start()
Start()
Main() - c:\Documents and Settings\Zlatko\My Documents\SharpDevelop
Projects\CS_script\CS_script\Main.cs:32,5 "

I have no means of running C# programs at present and can't claim much
expertise in any case. A guess is that a "valid Win32 application"
means an '.exe' file, not a '.py' file.

You are assuming that a Process object is as smart as the command
interpreter ('cmd.exe') and will know to use 'python.exe' for a file
with a 'py' extension?

What happens if you use 'python.exe' (or 'cmd.exe') as your file and
the script name as argument as in the code I posted?

Gerard
(PS. This group prefers that one doesn't top-post)

May 29 '06 #6

P: n/a
> >> "Gerard Flanagan" <gr********@yahoo.co.uk> je napisao u poruci interesnoj
grupi:11**********************@i39g2000cwa.googleg roups.com...
> tatamata wrote:
>> Hello.
>>
>> How can I run some Python script within C# program?
>>
>
> ---------------------------------------------------------------------------------
> ProcessStartInfo startInfo;
> Process process;
> string directory;
> string pyArgs;
> string script;
>
> startInfo = new ProcessStartInfo("python");
> startInfo.WorkingDirectory = directory;
> startInfo.Arguments = script + " " + pyArgs;
> startInfo.UseShellExecute = false;
> startInfo.CreateNoWindow = true;
> startInfo.RedirectStandardOutput = true;
> startInfo.RedirectStandardError = true;
>
> process = new Process();
> process.StartInfo = startInfo;
> process.Start();
>
> string s;
> while ((s = process.StandardOutput.ReadLine()) != null)
> {
> //do something with s
> }
> ---------------------------------------------------------------------------------
>
tatamata wrote:
Hello. I tried to implement ypour suggestion, but an error apears:
"Exception System.ComponentModel.Win32Exception was thrown in debugee:
The specified executable is not a valid Win32 application.

namespace CS_script
{
class MainClass
{
public static void Main(string[] args)
{

System.Diagnostics.ProcessStartInfo psi =new
System.Diagnostics.ProcessStartInfo();
psi.FileName="my_script.py";
psi.WorkingDirectory=Environment.CurrentDirectory;
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;

System.Diagnostics.Process script;
script = System.Diagnostics.Process.Start(psi);

System.IO.StreamReader myOutput = script.StandardOutput;
script.WaitForExit(2000);
if (script.HasExited)
{
string output = myOutput.ReadToEnd();
//this.processResults.Text = output;
}
MessageBox.Show("finished!");
}
}
}

When running the program, I have the following error:

"Exception System.ComponentModel.Win32Exception was thrown in debugee:
The specified executable is not a valid Win32 application.

StartWithCreateProcess()
Start()
Start()
Main() - c:\Documents and Settings\Zlatko\My Documents\SharpDevelop
Projects\CS_script\CS_script\Main.cs:32,5 "

I have no means of running C# programs at present and can't claim much
expertise in any case. A guess is that a "valid Win32 application"
means an '.exe' file, not a '.py' file.

You are assuming that a Process object is as smart as the command
interpreter ('cmd.exe') and will know to use 'python.exe' for a file
with a 'py' extension?

What happens if you use 'python.exe' (or 'cmd.exe') as your file and
the script name as argument as in the code I posted?

Gerard
(PS. This group prefers that one doesn't top-post)

tatamata wrote: Hello. It seems that the following code works. And it seems that Process
object can automatically run script by using python.exe, but only if
standard output is not redirected...

class MainClass
{
public static void Main(string[] args)
{
MyProcess myProcess = new MyProcess();
myProcess.ExecuteScript();
MessageBox.Show("Continue?","Application",
MessageBoxButtons.OKCancel);
}
}
public class MyProcess
{
// These are the Win32 error code for file not found or access
denied.
const int ERROR_FILE_NOT_FOUND =2;
const int ERROR_ACCESS_DENIED = 5;

/// <summary>
/// Executes a python script.
/// </summary>
public void ExecuteScript()
{
Process myProcess = new Process();

try
{
// Get the path that stores the python script.
//string myDocumentsPath
=Environment.GetFolderPath(Environment.SpecialFold er.Personal);
//If the script is placed in the same folder as C#
executable, set the path to current directory:
string myDocumentsPath=Environment.CurrentDirectory;

//Set the fully qualified script name
myProcess.StartInfo.FileName = myDocumentsPath +
"\\my_script.py";

//Execute the script:
myProcess.Start();

// Wait for it to die...
myProcess.WaitForExit();

MessageBox.Show ("Python script is successfully executed!");

}
catch (Win32Exception e)
{
if(e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
{
Console.WriteLine(e.Message + ". Check the path.");
}

else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
{
// Note that if your word processor might generate
exceptions
// such as this, which are handled first.
Console.WriteLine(e.Message +
". You do not have permission to print this file.");
}
}
}
}

Greetings,

Zlatko


Ok. Glad you have a successful outcome. See the following for an
asynchronous approach with multiple threads:

http://www.codeproject.com/csharp/launchprocess.asp

(PS. This group prefers that one doesn't top-post)


Gerard

May 30 '06 #7

This discussion thread is closed

Replies have been disabled for this discussion.