VM C#脚本 调用命令行 以python为例
首先:C# 脚本上面: 几乎不用变 注意VM脚本 字符串不支持 $符号;
public string ExecuteCommand(string command)
{
string output = string.Empty; // 用于存储命令的输出
string error = string.Empty; // 用于存储命令的错误信息
try
{
using (Process p = new Process()) // 使用Process类启动新进程
{
// 配置进程启动信息
p.StartInfo.FileName = "cmd.exe"; // 设置要启动的程序为cmd.exe
p.StartInfo.Arguments = "/c "+command; /c 参数表示执行完命令后关闭cmd窗口
p.StartInfo.UseShellExecute = false; // 不使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true; // 重定向标准输入
p.StartInfo.RedirectStandardOutput = true; // 重定向标准输出
p.StartInfo.RedirectStandardError = true; // 重定向错误输出
p.StartInfo.CreateNoWindow = true; // 不显示命令窗口
// p.StartInfo.CreateNoWindow = false;
p.Start(); // 启动进程
// 读取命令的输出
output = p.StandardOutput.ReadToEnd();
// 读取命令的错误信息
error = p.StandardError.ReadToEnd();
p.WaitForExit(); // 等待进程结束
}
}
catch (Exception ex)
{
// 捕获异常并返回错误信息
return "执行命令时发生错误: "+ex.Message;
}
// 如果有错误信息,返回错误信息;否则返回命令的输出
return string.IsNullOrEmpty(error) ? output : "错误: "+error;
}
接下来写python:
import os,sys,time
import mmap
import cv2
import numpy as np
import datetime
from matplotlib import pyplot as plt
from PIL import Image
print(sys.argv[0])
print(sys.argv[1])
print(sys.argv[2])
print(sys.argv[3])
print(sys.argv[4])
def get_module_path():
# 获取模块文件的绝对路径
module_path = os.path.abspath(__file__)
return module_path
def get_module_directory():
# 获取模块文件的绝对路径
module_path = os.path.abspath(__file__)
# 获取模块所在的目录
module_directory = os.path.dirname(module_path)
return module_directory
module_dir=get_module_directory()
print(module_dir)
# 打开图片文件
image_path = rf"{module_dir}\lena.jpg" # 替换为你的图片文件路径
#注意 这里 python作为被调用者 os.getcwd()输出的是 调用者的路径
#lena.jpg 如果没有在调用者的同级目录 就需要指定路径
image = Image.open(image_path)
#image.show()# 显示图片
需要注意的是 python作为被调用者 那么os.getcwd()输出的是 调用者的路径
#lena.jpg 如果没有在调用者的同级目录 就需要指定路径
get_module_directory() 输出模块的路径 也就是python脚本路径
sys.argv传输的是命令行传过来的运行参数
好了 开始在VM上面运行一下试试: 这里需要指定python文件的路径
public bool Process()
{
//Run();
//@"C:\Users\Administrator\AppData\Local\Programs\Python\Python38\python.exe
out0= ExecuteCommand(@"python C:\Users\Administrator\Desktop\okkl\WindowsFormsApp5\bin\x64\Debug\其他\show.py 111 222 333 444");
return true;
}
好看看运行结果:
python的输出被定向回来了. 哈哈哈
结束
当然C#也是一模一样的噢.