1.C# 调用python

本质上是使用命令行运行python

1.1 C# 使用命令行

program.cs

using System;
using System.Diagnostics;
using System.IO; namespace test
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
string result = p.run_cmd("ping.exe", "8.8.8.8 -n 2");
Console.WriteLine(result); Console.ReadKey();
} public string run_cmd(string program, string cmd)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = program;
start.Arguments = cmd;
start.UseShellExecute = false; // Do not use OS shell
start.CreateNoWindow = true; // We don't need new window
start.RedirectStandardOutput = true; // Any output, generated by application will be redirected back
start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = process.StandardError.ReadToEnd();
if (result == null || result == "")
{
result = reader.ReadToEnd();
}
return result;
}
}
}
}
}

代码运行结果

  • 调用run_cmd相当于执行了cmd命令,所以就有了使用命令行运行python脚本的方式

1.2. C# 调用 python3脚本

假设C盘根目录下有如下脚本 test1.py

import sys

def add(a,b):
return a+b if __name__ == "__main__":
print(sys.argv[1])
print("hello python")

program.cs 中加入函数runPython,并修改main函数

static void Main(string[] args)
{
Program p = new Program();
//string result = p.run_cmd("ping.exe", "8.8.8.8 -n 2");
string result = p.runPython("C:\\test1.py", "\"Form C#:\"");
Console.WriteLine(result); Console.ReadKey();
} public string runPython(string filename, string cmd)
{
string cmd1 = string.Format("{0} {1}", filename, cmd);
return run_cmd("python.exe", cmd1);
}

代码运行结果

1.3 C# 调用python3内的函数

我们知道使用python -c可以直接执行python代码,所以合理构造语句就可以直接调用python脚本内的函数了:python -c "print('hello python')"
若要调用脚本里的函数,常规写法为:

import sys
sys.path.append('c:\\')
import test1
print(test1.add(3,4))

缩成一行就是python -c "import sys;sys.path.append('c:\\');import test1;print(test1.add(3,4))"

program.cs 中加入函数runPyFunc,并修改main函数

        static void Main(string[] args)
{
Program p = new Program();
//string result = p.run_cmd("ping.exe", "8.8.8.8 -n 2");
//string result = p.runPython("C:\\test.py", "\"Form C#:\"");
string result = p.runPyFunc(@"C:\\","test1","add","3,4");
Console.WriteLine(result); Console.ReadKey();
} public string runPyFunc(string path, string filename, string functionname, string parameter)
{
string cmd = string.Format("-c \"import sys;sys.path.append('{0}');import {1};print({1}.{2}({3}))\"", path, filename, functionname, parameter);
return run_cmd("python.exe", cmd);
}

运行就可以得到结果“7”了

C# 调用 python3的更多相关文章

  1. sublime COMMAND + B 调用 python3 运行

    用sublime写了python3的代码,COMMAND + B运行调用 PYTHON3 我们先来新建一个sublime build system 然后自动打开了一个文本,清空并写入以下内容: { & ...

  2. notepad++调用python3中文乱码

    使用notepad++,配置好快捷键调用python3,一切就绪,仿佛就差代码了,结果一使用, 中文乱码,一直没有好的解决办法. 最后只能在代码中增加一行重写向输出解决,示例如下: #!/usr/bi ...

  3. C++ 调用Python3

    作为一种胶水语言,Python 能够很容易地调用 C . C++ 等语言,也能够通过其他语言调用 Python 的模块. Python 提供了 C++ 库,使得开发者能很方便地从 C++ 程序中调用 ...

  4. C++程序调用python3

    今天想做一个简单的管理密码的小程序,由于最近了解了下Python,就想用Python来写.但是看了看Python的界面库用法有感觉有点麻烦,所以还不如直接使用MFC写写界面,关于csv的文件处理部分使 ...

  5. python2.7和python3共存

    python2.7和python3共存 原本装了python,玩nodejs的时候需要node-gyp来编译依赖,无赖这货需要python2.5<v<3.0,那就弄两个版本吧 转载自 ht ...

  6. Linux下编译安装python3

    Linux下默认系统自带python2.6的版本,这个版本被系统很多程序所依赖,所以不建议删除,如果使用最新的Python3那么我们知道编译安装源码包和系统默认包之间是没有任何影响的,所以可以安装py ...

  7. Windows2012中Python2.7.11+Python3.4.4+Pycharm

    下载软件包 Python2.7.11:  https://www.python.org/ftp/python/2.7.11/python-2.7.11.amd64.msi Python3.4.4:   ...

  8. 超详细的 Linux CentOS 编译安装python3

    前言: 安装完CentOS7后,执行#Python与#python -V,看到版本号是2.6,而且之前写的都是跑在python3.X上面的,3.X和2.X有很多不同,在这里我就不弊述两者之间的区别了新 ...

  9. 如何在命令行中让python2和python3同存

    初学python,你可能同时安装了python2和3.在我们安装好python之后,我们会面临这样一个问题,在命令行输入"python",可能会出错,或者只能调用其中一个版本,py ...

随机推荐

  1. Python爬取链家二手房源信息

    爬取链家网站二手房房源信息,第一次做,仅供参考,要用scrapy.   import scrapy,pypinyin,requests import bs4 from ..items import L ...

  2. php 大数组 foreach 循环嵌套的性能优化

    前提:最近在做后台的时候,页面加载太慢,故第一时间想到的自然是优化SQL, 优化后sql查询速度从 2秒变成了零点几秒, 以为就这麽完事了,然并卵,加载竟然花费30秒! 这麽慢,然后在代码中分块记录它 ...

  3. 在React native 如何写if判断和for循环

    在vue中一般在需要判断时都是通过if语句来实现的,但是在react native中一般则通过三元运算法来实现. 具体代码如下所示. import React from 'react'; import ...

  4. C语言程序设计II—第十周教学

    第十周教学总结(29/4-5/5) 教学内容 本周的教学内容为:9.2 学生成绩排序 知识点:结构数组的定义.初始化和数组成员引用:9.3 修改学生成绩 知识点:结构指针指向操作,结构指针作为函数参数 ...

  5. 1、2 建立list(RestController),并postman测试

    1.主义实体类id   为String 类型(有用) @Entity(name = "t_student") public class Student { @Id private ...

  6. 【转帖】一文看懂docker容器技术架构及其中的各个模块

    一文看懂docker容器技术架构及其中的各个模块 原创 波波说运维 2019-09-29 00:01:00 https://www.toutiao.com/a6740234030798602763/ ...

  7. SrpingBoot入门到入坟02-HelloWorld的细节和初始自动配置

    关于SpringBoot的第一个HelloWorld的一些细节: 1.父项目 首先查看项目中的pom.xml文件 文件中有个父项目,点进去则: 它里面也有一个父项目,再点进去: 可以发现有很多的依赖版 ...

  8. C++:顺序表类实现约瑟夫问题_密码不同

    //.h #pragma once #include <iostream> using namespace std; #define MAXSIZE 100 template <cl ...

  9. JDBC(Java项目使用Oracle数据库)

    Java项目中使用Oracle数据库(Eclipse) 前言 这学期选了Oracle数据库这门课,于是自己下载了Oracle11gR2版本的数据库.在这之前我一直用的是MySQL.虽然两者教程差不多, ...

  10. java之理解面向对象

    1.程序设计的三种基本结构 顺序结构 顺序结构表示程序中的各操作是按照它们在源代码中的排列顺序依次执行的 选择结构 选择结构表示程序的处理需要根据某个特定的条件选择其中的一个分支执行.选择结构有单选择 ...