starting some Python script from C#

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • tatamata

    starting some Python script from C#

    Hello.

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

    Thanks,

    Zlatko


  • Gerard Flanagan

    #2
    Re: starting some Python script from C#

    tatamata wrote:[color=blue]
    > Hello.
    >
    > How can I run some Python script within C# program?
    >[/color]

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

    Comment

    • tatamata

      #3
      Re: starting some Python script from C#

      thanks.

      "Gerard Flanagan" <grflanagan@yah oo.co.uk> je napisao u poruci interesnoj
      grupi:114872894 0.440692.166330 @i39g2000cwa.go oglegroups.com. ..[color=blue]
      > tatamata wrote:[color=green]
      >> Hello.
      >>
      >> How can I run some Python script within C# program?
      >>[/color]
      >
      > ---------------------------------------------------------------------------------
      > 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
      >[/color]


      Comment

      • tatamata

        #4
        Re: starting some Python script from C#

        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" <grflanagan@yah oo.co.uk> je napisao u poruci interesnoj
        grupi:114872894 0.440692.166330 @i39g2000cwa.go oglegroups.com. ..[color=blue]
        > tatamata wrote:[color=green]
        >> Hello.
        >>
        >> How can I run some Python script within C# program?
        >>[/color]
        >
        > ---------------------------------------------------------------------------------
        > 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
        >[/color]


        Comment

        • Gerard Flanagan

          #5
          Re: starting some Python script from C#

          > "Gerard Flanagan" <grflanagan@yah oo.co.uk> je napisao u poruci interesnoj[color=blue]
          > grupi:114872894 0.440692.166330 @i39g2000cwa.go oglegroups.com. ..[color=green]
          > > tatamata wrote:[color=darkred]
          > >> Hello.
          > >>
          > >> How can I run some Python script within C# program?
          > >>[/color]
          > >
          > > ---------------------------------------------------------------------------------
          > > 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
          > > }
          > > ---------------------------------------------------------------------------------
          > >[/color][/color]

          tatamata wrote:[color=blue]
          > 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 "
          >[/color]


          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)

          Comment

          • tatamata

            #6
            Re: starting some Python script from C#

            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" <grflanagan@yah oo.co.uk> je napisao u poruci interesnoj
            grupi:114881519 4.860060.43810@ j73g2000cwa.goo glegroups.com.. .[color=blue][color=green]
            >> "Gerard Flanagan" <grflanagan@yah oo.co.uk> je napisao u poruci interesnoj
            >> grupi:114872894 0.440692.166330 @i39g2000cwa.go oglegroups.com. ..[color=darkred]
            >> > 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
            >> > }
            >> > ---------------------------------------------------------------------------------
            >> >[/color][/color]
            >
            > tatamata wrote:[color=green]
            >> 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 "
            >>[/color]
            >
            >
            > 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)
            >[/color]


            Comment

            • Gerard Flanagan

              #7
              Re: starting some Python script from C#

              > >> "Gerard Flanagan" <grflanagan@yah oo.co.uk> je napisao u poruci interesnoj[color=blue][color=green][color=darkred]
              > >> grupi:114872894 0.440692.166330 @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
              > >> > }
              > >> > ---------------------------------------------------------------------------------
              > >> >[/color]
              > >
              > > tatamata wrote:[color=darkred]
              > >> 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 "
              > >>[/color]
              > >
              > >
              > > 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)
              > >[/color][/color]

              tatamata wrote:[color=blue]
              > 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
              >[/color]

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


              [color=blue][color=green]
              > >
              > > (PS. This group prefers that one doesn't top-post)
              > >[/color][/color]

              Gerard

              Comment

              Working...