A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 陈君 金牌黑马   /  2014-9-3 23:54  /  707 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

c#执行外部命令示例分享,大家参考使用吧

  1. String Command = @"python test.py";
  2. String Output = Execute.run(Command);
  3. Console.WriteLine(Output);
  4. <DIV class=blockcode>
  5. <BLOCKQUOTE>
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. //using before change the namespace
  13. namespace test.utility
  14. {
  15. class Execute
  16. {
  17. public static String run(String Command)
  18. {
  19. String Output = null;
  20. if (Command != null && !Command.Equals(""))
  21. {
  22. Process process = new Process();
  23. ProcessStartInfo processStartInfo = new ProcessStartInfo();
  24. processStartInfo.FileName = "cmd.exe";
  25. //no create the cmd windows
  26. processStartInfo.CreateNoWindow = true;
  27. processStartInfo.RedirectStandardInput = true;
  28. processStartInfo.RedirectStandardOutput = true;
  29. processStartInfo.RedirectStandardError = true;
  30. processStartInfo.UseShellExecute = false;
  31. process.StartInfo = processStartInfo;
  32. try
  33. {
  34. process.Start();
  35. process.StandardInput.WriteLine(Command);
  36. process.StandardInput.WriteLine("exit");
  37. process.WaitForExit(30 * 1000);
  38. Output = process.StandardOutput.ReadToEnd();
  39. }
  40. catch (Exception e)
  41. {
  42. process.Close();
  43. return e.ToString();
  44. }
  45. finally
  46. {
  47. process.Close();
  48. }
  49. }
  50. return ContextFilter(Output);
  51. }
  52. public static String ContextFilter(String Output)
  53. {
  54. Regex regex_end = new Regex("^[^^]*#end");
  55. Match match = regex_end.Match(Output);
  56. Regex regex_begin = new Regex("^[^^]*?#begin\r\n");
  57. String result = regex_begin.Replace(match.Value, "");
  58. Regex regex_tar = new Regex("\r\n#end$");
  59. result = regex_tar.Replace(result,"");
  60. return result;
  61. }
  62. }
  63. }
复制代码



0 个回复

您需要登录后才可以回帖 登录 | 加入黑马