如何从C#运行Python脚本?

weixin_38060040 2019-09-12 11:28:55
之前已经在不同程度上提出了这类问题,但我觉得它没有以简洁的方式回答,所以我再次提出这个问题. 我想用Python运行一个脚本.让我们说是这样的: if __name__ == '__main__': with open(sys.argv[1], 'r') as f: s = f.read() print s 获取文件位置,读取它,然后打印其内容.没那么复杂. 好的,那我怎么在C#中运行呢? 这就是我现在拥有的: private void run_cmd(string cmd, string args) { ProcessStartInfo start = new ProcessStartInfo(); start.FileName = cmd; start.Arguments = args; start.UseShellExecute = false; start.RedirectStandardOutput = true; using (Process process = Process.Start(start)) { using (StreamReader reader = process.StandardOutput) { string result = reader.ReadToEnd(); Console.Write(result); } } } 当我将code.py位置作为cmd传递,文件名位置作为args时,它不起作用.我被告知我应该将python.exe作为cmd传递,然后将code.py文件名作为args传递. 我一直在寻找一段时间,只能找到建议使用IronPython等的人.但是必须有一种从C#调用Python脚本的方法. 一些澄清: 我需要从C#运行它,我需要捕获输出,我不能使用IronPython或其他任何东西.无论你有什么黑客都没关系. P.S.:我正在运行的实际Python代码比这复杂得多,它返回我在C#中需要的输出,而C#代码将不断调用Python. 假装这是我的代码: private void get_vals() { for (int i = 0; i < 100; i++) { run_cmd("code.py", i); } }
...全文
433 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38063433 2019-09-12
  • 打赏
  • 举报
回复
它不起作用的原因是因为你有UseShellExecute = false. 如果不使用shell,则必须提供python可执行文件的完整路径作为FileName,并构建Arguments字符串以提供脚本和要读取的文件. 另请注意,除非UseShellExecute = false,否则不能使用RedirectStandardOutput. 我不太确定如何为python格式化参数字符串,但是你需要这样的东西: private void run_cmd(string cmd, string args) { ProcessStartInfo start = new ProcessStartInfo(); start.FileName = "my/full/path/to/python.exe"; start.Arguments = string.Format("{0} {1}", cmd, args); start.UseShellExecute = false; start.RedirectStandardOutput = true; using(Process process = Process.Start(start)) { using(StreamReader reader = process.StandardOutput) { string result = reader.ReadToEnd(); Console.Write(result); } } }

476

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧