大佬教程收集整理的这篇文章主要介绍了如何从python脚本在C#中异步读取数据,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试从 WPF C# 连续读取 python 脚本输出(在 python 中,我正在跟踪一个彩色球并打印它的 x、y 和半径)。
using (var requester = new ZSocket(ZSocketType.REQ))
{
// Connect
requester.Connect("tcp://127.0.0.1:5555");
for (; ; )
{
String requestText = "Hello";
Console.Write("Sending {0}...",requestText);
// Send
requester.Send(new ZFrame(requestText));
// Receive
using (ZFrame reply = requester.ReceiveFrame())
{
Console.Writeline(" Received: {0} {1}!",requestText,reply.ReadString());
}
}
}
private voID Window_Loaded(object sender,RoutedEventArgs E)
{
String python = @"C:\Desktop\test\venv\Scripts\python.exe";
// python app to call
String myPythonApp = @"C:\Users\Desktop\test\main.py";
// Create new process start info
processstarTinfo myprocessstarTinfo = new processstarTinfo(python);
// make sure we can read the output from stdout
myprocessstarTinfo.UseSHellExecute = false;
myprocessstarTinfo.RedirectStandardOutput = true;
myprocessstarTinfo.Arguments = myPythonApp;
Process myProcess = new Process();
// assign start information to the process
myProcess.StarTinfo = myprocessstarTinfo;
// start the process
myProcess.OutputDataReceived += MyProcess_OutputDataReceived;
myProcess.Start();
myProcess.beginoutputReadline();
// Read the standard output of the app we called.
// in order to avoID deadlock we will read output first
// and then wait for process terminate:
//StreamReader myStreamReader = myProcess.StandardOutput;
//String myString = myStreamReader.Readline();
//await myStreamReader.ReadAsync(result,(int)R_608_11845@yStreamReader.baseStream.Length);
// wait exit signal from the app we called and then close it.
//myProcess.WaitForExit();
//myProcess.Close();
// write the output we got from python app
//Console.Writeline("Value received from script: " + myString);
}
private voID MyProcess_OutputDataReceived(object sender,DataReceivedEventArgs E)
{
Console.Writeline("++++");
}
Console.Writeline("hi");
for (; ; )
{
if (file.Exists(textfilE))
{
using (StreamReader file = new StreamReader(textfilE))
{
int counter = 0;
String ln;
while ((ln = file.Readline()) != null)
{
Console.Writeline(ln);
counter++;
}
file.Close();
}
}
所有情况下python都持有线程并且不允许c#访问它。现在我正在使用 2 种方法,即从 Process 获取数据,但 MyProcess_OutputDataReceived 没有触发。
import sys
from collections import deque
from PIL import Image,ImageOps,ImageDraw
import numpy as np
import argparse
import imutils
import cv2
import time
import pandas as pd
import matplotlib.pyplot as plt
#import zmq
#context = zmq.Context()
#socket = context.socket(zmq.REp)
#socket.bind("tcp://*:5555")
#object tracking def start
ap = argparse.ArgumentParser()
ap.add_argument("-v","--vIDeo",Help="path to the (optional) vIDeo file")
ap.add_argument("-b","--buffer",type=int,default=64,Help="max buffer size")
args = vars(ap.parse_args())
greenLower = (29,86,6)
greenUpper = (64,255,255)
pts = deque(maxlen=args["buffer"])
if not args.get("vIDeo",falsE):
camera = cv2.VIDeoCapture(0)
else:
camera = cv2.VIDeoCapture(args["vIDeo"])
Data_Features = ['x','y','time']
Data_Points = pd.DataFrame(data=None,columns=Data_Features,dtype=float)
start = time.time()
#object tracking def end
#file1 = open("myfile.txt","w")
#L = ["This is Delhi \n","This is Paris \n","This is London \n"]
#file1.write("Hello \n")
#file1.writelines(L)
#file1.close()
while True:
# Wait for next request from clIEnt
#message = socket.recv()
#print("Received request: %s" % messagE)
# Do some 'work'
#time.sleep(1)
# Send reply BACk to clIEnt
#socket.send("World")
#object track vIDs start
(grabbed,framE) = camera.read()
current_time = time.time() - start
if args.get("vIDeo") and not grabbed:
break
frame = imutils.resize(frame,wIDth=1600)
# frame2 = imutils.resize
#blurred = cv2.GaussianBlur(frame,(11,11),0)
hsv = cv2.cvtcolor(frame,cv2.color_BGR2HSV)
mask = cv2.inRange(hsv,greenLower,greenUpper)
mask = cv2.erode(mask,None,iterations=2)
mask = cv2.dilate(mask,iterations=2)
cnts = cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]
center = None
if len(cnts) > 0:
# find the largest contour in the mask,then use
# it to compute the minimum enclosing circle and
# centroID
c = max(cnts,key=cv2.contourArea)
((x,y),radius) = cv2.minenclosingCircle(C)
M = cv2.moments(C)
center = (int(M["m10"] / M["m00"]),int(M["m01"] / M["m00"]))
# only proceed if the radius meets a minimum size
if (radius < 300) & (radius > 10):
# draw the circle and centroID on the frame,# then update the List of tracked points
cv2.circle(frame,(int(X),int(y)),int(radius),(0,255),2)
sys.stdout.write(str(X) + '\n')
#print(str(X))
#file1 = open("myfile.txt","w")
#file1.write(str(X))
#file1.close()
#time.sleep(1)
cv2.circle(frame,center,5,-1)
# Save The Data Points
Data_Points.loc[Data_Points.size / 3] = [x,y,current_time]
pts.appendleft(center)
for i in range(1,len(pts)):
# if either of the tracked points are None,ignore
# them
if pts[i - 1] is None or pts[i] is None:
conTinue
# otherwise,compute the thickness of the line and
# draw the connecTing lines
thickness = int(np.sqrt(args["buffer"] / float(i + 1)) * 2.5)
cv2.line(frame,pts[i - 1],pts[i],thickness)
cv2.imshow("Frame",framE)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
#object tracking vIDs end
h = 0.2
X0 = -3
Y0 = 20
time0 = 0
theta0 = 0.3
# Applying the correction terms to obtain actual experimental data
Data_Points['x'] = Data_Points['x'] - X0
Data_Points['y'] = Data_Points['y'] - Y0
Data_Points['time'] = Data_Points['time'] - time0
# Calulataion of theta value
Data_Points['theta'] = 2 * np.arctan(
Data_Points['y'] * 0.0000762 / h) # the factor correspons to pixel length in real life
Data_Points['theta'] = Data_Points['theta'] - theta0
# CreaTing the 'Theta' vs 'Time' plot
plt.plot(Data_Points['theta'],Data_Points['time'])
plt.xlabel('Theta')
plt.ylabel('Time')
# Export The Data Points As cvs file and plot
Data_Points.to_csv('Data_Set.csv',sep=",")
plt.savefig('Time_vs_Theta_Graph.svg',transparent=TruE)
# cleanup the camera and close any open windows
camera.release()
cv2.destroyAllwindows()
请帮帮我。 提前致谢。
兰吉斯
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
以上是大佬教程为你收集整理的如何从python脚本在C#中异步读取数据全部内容,希望文章能够帮你解决如何从python脚本在C#中异步读取数据所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。