PTVS

Python tools for Visual Studio 免费开源的VisualStudio的插件,支持 VisualStudio 2010/2012/2013

IronPython

NuGet 包管理器 -> NuGet 包,搜索 IronPython 包安装

命名空间

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

创建,环境配置

不包含第三方模块的调用方式

1
2
3
4
5
6
7
8
//创建Python解释器对象
ScriptRuntime pyRunTime = Python.CreateRuntime();
//读取脚本文件
dynamic py = pyEngine.ExecuteFile(@"test.py");

//调用脚本文件中对应的函数
int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };
string reStr = py.main(array);
1
2
3
4
5
6
7
8
def main(arr):
try:
arr = set(arr)
arr = sorted(arr)
arr = arr[0:]
return str(arr)
except Exception as err:
return str(err)

包含第三方模块的调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Process p = new Process();
//待处理python文件的路径,本例中放在debug文件夹下
string path = "reset_ipc.py";
string sArguments = path;
ArrayList arrayList = new ArrayList(){
"com4", 57600, "password"
}
//添加参数
foreach (var param in arrayList)
{
sArguments += " " + sigstr;
}

//python2.7的安装路径
p.StartInfo.FileName = @"D:\Python2\python.exe";
//python命令的参数
p.StartInfo.Arguments = sArguments;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
//启动进程
p.Start();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# -*- coding: UTF-8 -*-
import serial
import time

def resetIPC(com, baudrate, password, timeout=0.5):
ser = serial.Serial(com, baudrate, timeout=timeout)
flag = True
try:
ser.close()
ser.open()
ser.write("\n".encode("utf-8"))
time.sleep(1)
ser.write("root\n".encode("utf-8"))
time.sleep(1)
passwordStr="%s\n" % password
ser.write(passwordStr.encode("utf-8"))
time.sleep(1)
ser.write("killall -9 xxx\n".encode("utf-8"))
time.sleep(1)
ser.write("rm /etc/xxx/xxx_user.*\n".encode("utf-8"))
time.sleep(1)
ser.write("reboot\n".encode("utf-8"))
time.sleep(1)
except Exception:
flag = False
finally:
ser.close()
return flag

resetIPC(sys.argv[1], sys.argv[2], sys.argv[3])

c#项目调用Python模块