473,388 Members | 1,277 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

starting some Python script from C#

Hello.

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

Thanks,

Zlatko
May 27 '06 #1
6 9858
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
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
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
> "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
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
> >> "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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: David Klaffenbach | last post by:
Is there a way from within a python script to cause the interpreter to be in interactive mode after the script finishes? so that if I run: myscript.py it will always execute as if I had...
22
by: Brad Tilley | last post by:
Is it possible to write a file open, then read program in C and then call the C program from a Python script like this: for root, files, dirs in os.walk(path) for f in files: try:...
8
by: Jan Gregor | last post by:
Hello I run python script on another computer and want to "survive" that script after my logout. the script also uses drive mapping to network drive. Can you help me ? Or better is there some...
1
by: neha | last post by:
hi, i m trying to integrate python with apache on linux.For this i m using mod_python. I dont see any problem with the versions of python,apache and mod_python i m using. the versions i m using...
1
by: dfaber | last post by:
Aloha! I want to terminate a process/program from within a python script. For example, if I have a program say foo.sh that starts running, then I can run it from within a python script using...
8
by: flit | last post by:
Hello All, I am trying to get information from a form and send it to a python script without success.. Here is my objective: User enters data in form --form send variables to python script...
3
by: telduivel | last post by:
Can someone please help me with this: I have a python script, that at some point calls a linux bash script (.sh). Starting the shell script is the last thing my python script needs to do, so I...
1
by: Aspersieman | last post by:
Hi All I have a windows service (attached file). I basically just calls another script every 60 seconds. I can install, start and stop this service as expected with: ParseMailboxService.py...
1
by: Gros Bedo | last post by:
Yes I've seen that each python script calls its own instance of Python. Buthow to know which is the good one in bash ? Is there a command that gets the parameters of process, so I could use grep to...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.