473,588 Members | 2,474 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

starting some Python script from C#

Hello.

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

Thanks,

Zlatko
May 27 '06 #1
6 9912
tatamata wrote:
Hello.

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


---------------------------------------------------------------------------------
ProcessStartInf o startInfo;
Process process;
string directory;
string pyArgs;
string script;

startInfo = new ProcessStartInf o("python");
startInfo.Worki ngDirectory = directory;
startInfo.Argum ents = script + " " + pyArgs;
startInfo.UseSh ellExecute = false;
startInfo.Creat eNoWindow = true;
startInfo.Redir ectStandardOutp ut = true;
startInfo.Redir ectStandardErro r = true;

process = new Process();
process.StartIn fo = startInfo;
process.Start() ;

string s;
while ((s = process.Standar dOutput.ReadLin e()) != null)
{
//do something with s
}
---------------------------------------------------------------------------------

HTH

Gerard

May 27 '06 #2
thanks.

"Gerard Flanagan" <gr********@yah oo.co.uk> je napisao u poruci interesnoj
grupi:11******* *************** @i39g2000cwa.go oglegroups.com. ..
tatamata wrote:
Hello.

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


---------------------------------------------------------------------------------
ProcessStartInf o startInfo;
Process process;
string directory;
string pyArgs;
string script;

startInfo = new ProcessStartInf o("python");
startInfo.Worki ngDirectory = directory;
startInfo.Argum ents = script + " " + pyArgs;
startInfo.UseSh ellExecute = false;
startInfo.Creat eNoWindow = true;
startInfo.Redir ectStandardOutp ut = true;
startInfo.Redir ectStandardErro r = true;

process = new Process();
process.StartIn fo = startInfo;
process.Start() ;

string s;
while ((s = process.Standar dOutput.ReadLin e()) != null)
{
//do something with s
}
---------------------------------------------------------------------------------

HTH

Gerard

May 27 '06 #3
Hello. I tried to implement ypour suggestion, but an error apears:
"Exception System.Componen tModel.Win32Exc eption was thrown in debugee:
The specified executable is not a valid Win32 application.

StartWithCreate Process()
Start()
Start()
Main() - c:\Documents and Settings\Zlatko \My Documents\Sharp Develop
Projects\CS_scr ipt\CS_script\M ain.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.Collecti ons.Generic;
using System.Diagnost ics;
using System.Windows. Forms;

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

System.Diagnost ics.ProcessStar tInfo psi =new
System.Diagnost ics.ProcessStar tInfo();
psi.FileName="m y_script.py";
psi.WorkingDire ctory=Environme nt.CurrentDirec tory;
psi.RedirectSta ndardOutput = true;
psi.WindowStyle = System.Diagnost ics.ProcessWind owStyle.Hidden;
psi.UseShellExe cute = false;
psi.CreateNoWin dow = true;

System.Diagnost ics.Process script;
script = System.Diagnost ics.Process.Sta rt(psi);

System.IO.Strea mReader myOutput = script.Standard Output;
script.WaitForE xit(2000);
if (script.HasExit ed)
{
string output = myOutput.ReadTo End();
//this.processRes ults.Text = output;
}
MessageBox.Show ("finished!" );
}
}
}

When running the program, I have the following error:

"Exception System.Componen tModel.Win32Exc eption was thrown in debugee:
The specified executable is not a valid Win32 application.

StartWithCreate Process()
Start()
Start()
Main() - c:\Documents and Settings\Zlatko \My Documents\Sharp Develop
Projects\CS_scr ipt\CS_script\M ain.cs:32,5 "

"Gerard Flanagan" <gr********@yah oo.co.uk> je napisao u poruci interesnoj
grupi:11******* *************** @i39g2000cwa.go oglegroups.com. ..
tatamata wrote:
Hello.

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


---------------------------------------------------------------------------------
ProcessStartInf o startInfo;
Process process;
string directory;
string pyArgs;
string script;

startInfo = new ProcessStartInf o("python");
startInfo.Worki ngDirectory = directory;
startInfo.Argum ents = script + " " + pyArgs;
startInfo.UseSh ellExecute = false;
startInfo.Creat eNoWindow = true;
startInfo.Redir ectStandardOutp ut = true;
startInfo.Redir ectStandardErro r = true;

process = new Process();
process.StartIn fo = startInfo;
process.Start() ;

string s;
while ((s = process.Standar dOutput.ReadLin e()) != null)
{
//do something with s
}
---------------------------------------------------------------------------------

HTH

Gerard

May 28 '06 #4
> "Gerard Flanagan" <gr********@yah oo.co.uk> je napisao u poruci interesnoj
grupi:11******* *************** @i39g2000cwa.go oglegroups.com. ..
tatamata wrote:
Hello.

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

---------------------------------------------------------------------------------
ProcessStartInf o startInfo;
Process process;
string directory;
string pyArgs;
string script;

startInfo = new ProcessStartInf o("python");
startInfo.Worki ngDirectory = directory;
startInfo.Argum ents = script + " " + pyArgs;
startInfo.UseSh ellExecute = false;
startInfo.Creat eNoWindow = true;
startInfo.Redir ectStandardOutp ut = true;
startInfo.Redir ectStandardErro r = true;

process = new Process();
process.StartIn fo = startInfo;
process.Start() ;

string s;
while ((s = process.Standar dOutput.ReadLin e()) != null)
{
//do something with s
}
---------------------------------------------------------------------------------


tatamata wrote: Hello. I tried to implement ypour suggestion, but an error apears:
"Exception System.Componen tModel.Win32Exc eption 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.Diagnost ics.ProcessStar tInfo psi =new
System.Diagnost ics.ProcessStar tInfo();
psi.FileName="m y_script.py";
psi.WorkingDire ctory=Environme nt.CurrentDirec tory;
psi.RedirectSta ndardOutput = true;
psi.WindowStyle = System.Diagnost ics.ProcessWind owStyle.Hidden;
psi.UseShellExe cute = false;
psi.CreateNoWin dow = true;

System.Diagnost ics.Process script;
script = System.Diagnost ics.Process.Sta rt(psi);

System.IO.Strea mReader myOutput = script.Standard Output;
script.WaitForE xit(2000);
if (script.HasExit ed)
{
string output = myOutput.ReadTo End();
//this.processRes ults.Text = output;
}
MessageBox.Show ("finished!" );
}
}
}

When running the program, I have the following error:

"Exception System.Componen tModel.Win32Exc eption was thrown in debugee:
The specified executable is not a valid Win32 application.

StartWithCreate Process()
Start()
Start()
Main() - c:\Documents and Settings\Zlatko \My Documents\Sharp Develop
Projects\CS_scr ipt\CS_script\M ain.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.Collecti ons.Generic;
using System.Diagnost ics;
using System.Componen tModel;
using System.Windows. Forms;

namespace CS_script
{

class MainClass
{
public static void Main(string[] args)
{
MyProcess myProcess = new MyProcess();
myProcess.Execu teScript();
MessageBox.Show ("Continue?","A pplication",
MessageBoxButto ns.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_DE NIED = 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.Ge tFolderPath(Env ironment.Specia lFolder.Persona l);
//If the script is placed in the same folder as C#
executable, set the path to current directory:
string myDocumentsPath =Environment.Cu rrentDirectory;

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

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

//string output = myProcess.Stand ardOutput.ReadT oEnd();
//Console.WriteLi ne(output);

//Console.WriteLi ne(myProcess.St andardOutput.Re adToEnd());

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

// Wait for it to die...
myProcess.WaitF orExit();

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

}
catch (Win32Exception e)
{
if(e.NativeErro rCode == ERROR_FILE_NOT_ FOUND)
{
Console.WriteLi ne(e.Message + ". Check the path.");
}

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

Greetings,

Zlatko

"Gerard Flanagan" <gr********@yah oo.co.uk> je napisao u poruci interesnoj
grupi:11******* **************@ j73g2000cwa.goo glegroups.com.. .
"Gerard Flanagan" <gr********@yah oo.co.uk> je napisao u poruci interesnoj
grupi:11******* *************** @i39g2000cwa.go oglegroups.com. ..
> tatamata wrote:
>> Hello.
>>
>> How can I run some Python script within C# program?
>>
>
> ---------------------------------------------------------------------------------
> ProcessStartInf o startInfo;
> Process process;
> string directory;
> string pyArgs;
> string script;
>
> startInfo = new ProcessStartInf o("python");
> startInfo.Worki ngDirectory = directory;
> startInfo.Argum ents = script + " " + pyArgs;
> startInfo.UseSh ellExecute = false;
> startInfo.Creat eNoWindow = true;
> startInfo.Redir ectStandardOutp ut = true;
> startInfo.Redir ectStandardErro r = true;
>
> process = new Process();
> process.StartIn fo = startInfo;
> process.Start() ;
>
> string s;
> while ((s = process.Standar dOutput.ReadLin e()) != null)
> {
> //do something with s
> }
> ---------------------------------------------------------------------------------
>


tatamata wrote:
Hello. I tried to implement ypour suggestion, but an error apears:
"Exception System.Componen tModel.Win32Exc eption 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.Diagnost ics.ProcessStar tInfo psi =new
System.Diagnost ics.ProcessStar tInfo();
psi.FileName="m y_script.py";
psi.WorkingDire ctory=Environme nt.CurrentDirec tory;
psi.RedirectSta ndardOutput = true;
psi.WindowStyle = System.Diagnost ics.ProcessWind owStyle.Hidden;
psi.UseShellExe cute = false;
psi.CreateNoWin dow = true;

System.Diagnost ics.Process script;
script = System.Diagnost ics.Process.Sta rt(psi);

System.IO.Strea mReader myOutput = script.Standard Output;
script.WaitForE xit(2000);
if (script.HasExit ed)
{
string output = myOutput.ReadTo End();
//this.processRes ults.Text = output;
}
MessageBox.Show ("finished!" );
}
}
}

When running the program, I have the following error:

"Exception System.Componen tModel.Win32Exc eption was thrown in debugee:
The specified executable is not a valid Win32 application.

StartWithCreate Process()
Start()
Start()
Main() - c:\Documents and Settings\Zlatko \My Documents\Sharp Develop
Projects\CS_scr ipt\CS_script\M ain.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********@yah oo.co.uk> je napisao u poruci interesnoj
grupi:11******* *************** @i39g2000cwa.go oglegroups.com. ..
> tatamata wrote:
>> Hello.
>>
>> How can I run some Python script within C# program?
>>
>
> ---------------------------------------------------------------------------------
> ProcessStartInf o startInfo;
> Process process;
> string directory;
> string pyArgs;
> string script;
>
> startInfo = new ProcessStartInf o("python");
> startInfo.Worki ngDirectory = directory;
> startInfo.Argum ents = script + " " + pyArgs;
> startInfo.UseSh ellExecute = false;
> startInfo.Creat eNoWindow = true;
> startInfo.Redir ectStandardOutp ut = true;
> startInfo.Redir ectStandardErro r = true;
>
> process = new Process();
> process.StartIn fo = startInfo;
> process.Start() ;
>
> string s;
> while ((s = process.Standar dOutput.ReadLin e()) != null)
> {
> //do something with s
> }
> ---------------------------------------------------------------------------------
>
tatamata wrote:
Hello. I tried to implement ypour suggestion, but an error apears:
"Exception System.Componen tModel.Win32Exc eption 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.Diagnost ics.ProcessStar tInfo psi =new
System.Diagnost ics.ProcessStar tInfo();
psi.FileName="m y_script.py";
psi.WorkingDire ctory=Environme nt.CurrentDirec tory;
psi.RedirectSta ndardOutput = true;
psi.WindowStyle = System.Diagnost ics.ProcessWind owStyle.Hidden;
psi.UseShellExe cute = false;
psi.CreateNoWin dow = true;

System.Diagnost ics.Process script;
script = System.Diagnost ics.Process.Sta rt(psi);

System.IO.Strea mReader myOutput = script.Standard Output;
script.WaitForE xit(2000);
if (script.HasExit ed)
{
string output = myOutput.ReadTo End();
//this.processRes ults.Text = output;
}
MessageBox.Show ("finished!" );
}
}
}

When running the program, I have the following error:

"Exception System.Componen tModel.Win32Exc eption was thrown in debugee:
The specified executable is not a valid Win32 application.

StartWithCreate Process()
Start()
Start()
Main() - c:\Documents and Settings\Zlatko \My Documents\Sharp Develop
Projects\CS_scr ipt\CS_script\M ain.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.Execu teScript();
MessageBox.Show ("Continue?","A pplication",
MessageBoxButto ns.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_DE NIED = 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.Ge tFolderPath(Env ironment.Specia lFolder.Persona l);
//If the script is placed in the same folder as C#
executable, set the path to current directory:
string myDocumentsPath =Environment.Cu rrentDirectory;

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

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

// Wait for it to die...
myProcess.WaitF orExit();

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

}
catch (Win32Exception e)
{
if(e.NativeErro rCode == ERROR_FILE_NOT_ FOUND)
{
Console.WriteLi ne(e.Message + ". Check the path.");
}

else if (e.NativeErrorC ode == ERROR_ACCESS_DE NIED)
{
// Note that if your word processor might generate
exceptions
// such as this, which are handled first.
Console.WriteLi ne(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
1821
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 run: python23.exe -i myscript.py
22
6301
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: EXECUTE_C_PROGRAM If possible, how much faster would this be over a pure Python solution?
8
3233
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 info for unix person how to survive with python on windows ;-) thanks, jan gregor
1
2779
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 are apache version2. mod_python v3.1.14 python2.4 The problem is,when i m running my python script,after starting apache
1
1677
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 os.popen('foo.sh') which starts a program/process say 'bar' At some point later, I want to kill 'bar'. Currently, I start off the process and then when the python script exits, the process 'bar' is
8
1875
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 --> script runs and output result. the form code
3
5443
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 would like for the python script to exit once the call has been made, without waiting for the shell script to finish. My question is: how do I call a shell script from a python script? and how do I do that such that control is tranferred to the...
1
3025
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 install | start | stop The problem is: if I create an exe of this script (all required modules are included in the exe) with gui2exe (a frontend to py2exe) I can install the service - but not start it. The error it returns is "Error
1
2981
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 select the one containing the name of my script ? _________________________________________________________________ Votre contact a choisi Hotmail, l'e-mail nouvelle génération. Créezun compte. http://www.windowslive.fr/hotmail/default.asp
0
7929
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7862
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8357
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7987
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8223
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
3847
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3887
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2372
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1459
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.