用C#调用命令行运行Python文件


第一次运行的时候会请求Python路径,需要手动定位python.exe的位置

        /// <summary>
        /// C#里运行Python文件
        /// </summary>
        /// <param name="cmd">要运行的python文件</param>
        /// <param name="args">参数</param>
        public void RunScript(string cmd, string args)
        {
            ProcessStartInfo start = new ProcessStartInfo();
            bool exists = File.Exists(Settings.Default.PythonPath);

            if (Settings.Default.PythonPath.Equals("--") || !exists)
            {
                openFileDialog1.FileName = "";
                openFileDialog1.InitialDirectory = desktopPath;
                openFileDialog1.Filter = "Python Exe (python.exe)|*.exe|All files (*.*)|*.*";
                openFileDialog1.FilterIndex = 1;
                openFileDialog1.RestoreDirectory = true;

                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string fp = openFileDialog1.FileName;

                    int p = (int) Environment.OSVersion.Platform;

                    string pythonName;
                    // Unix/Linux pyton name. Used if run with mono.
                    // From the mono FAQ: http://www.mono-project.com/docs/faq/technical/
                    if ((p == 4) || (p == 6) || (p == 128))
                    {
                        pythonName = "python";
                    }
                    else
                    {
                        pythonName = "python.exe";
                    }

                    if (fp.Contains(pythonName))
                    {
                        Settings.Default.PythonPath = fp;
                        Settings.Default.Save();
                    }
                    else
                    {
                        MessageBox.Show("Python.exe not selected. Stopping.", "python.exe not found");
                        return;
                    }
                }
                else
                {
                    return;
                }
            }

            start.FileName = Settings.Default.PythonPath;
            start.Arguments = string.Format("{0} {1}", cmd, args);
            start.UseShellExecute = true;
            start.ErrorDialog = true;

            using (Process process = Process.Start(start))
            {
                process.WaitForExit();
            }
        }

转载自:https://blog.csdn.net/u010412858/article/details/78832068

You may also like...