In 2015 I have posted a question on SO how to Create DDE server in python and send data continously. The answer and code posted by JayleoPlayGround to that question back then worked flawlessly in python 2.7 and I have used it until recently.
As Python 2 is no longer actively supported from January 2020, I want to move my code to python 3. I have installed pywin32 (version 227) using pip on python 3.7.6 and tried to use the same code as before:
# coded by JayleoPlayGround
# use Portable Python 2.7.5.1 + pywin32-214
import time
import win32ui, dde
from pywin.mfc import object
class DDETopic(object.Object):
def __init__(self, topicName):
self.topic = dde.CreateTopic(topicName)
object.Object.__init__(self, self.topic)
self.items = {}
def setData(self, itemName, value):
try:
self.items[itemName].SetData( str(value) )
except KeyError:
if itemName not in self.items:
self.items[itemName] = dde.CreateStringItem(itemName)
self.topic.AddItem( self.items[itemName] )
self.items[itemName].SetData( str(value) )
ddeServer = dde.CreateServer()
ddeServer.Create('Orbitron')
ddeTopic = DDETopic('Tracking')
ddeServer.AddTopic(ddeTopic)
while True:
yourData = time.ctime() + ' UP0 DN145000001 UMusb DMfm AZ040 EL005 SNNO SATELLITE'
ddeTopic.setData('Tracking', yourData)
win32ui.PumpWaitingMessages(0, -1)
time.sleep(0.1)
When running the above code in python 3.7.6 and using pywin32 (version 227), the external DDE client application that I interface with is able to connect to the DDE server, but the data string is not received correctly. As described before, if I am using Python 2.7 with pywin32 (version 214) this works fine however.
As there are no error messages shown I am lost what the problem is under python 3. I tried all available pywin32 versions for this python version (222 to 227) without success. Any ideas on how to get this to work would be much appreciated.
Related
I was running a python script with the openai library. Whenever I run this function on my local machine it throws the following error
def gpt3_embedding(content, engine='text-embedding-ada-002'):
#delay_print('Making a vector')
content = content.encode(encoding='ASCII',errors='ignore').decode()
response = openai.Embedding.create(input=content,model=engine)
vector = response['data'][0]['embedding'] # this is a normal list
#delay_print('Vector returned')
return vector
AttributeError: module 'openai' has no attribute 'Embedding
NB : I am using the latest openai package and python 3.11.1
If all goes well, the error shouldnt appear at all.
I tested your code with:
Python 3.11.1 and OpenAI Python library 0.25.0
Python 3.11.1 and OpenAI Python library 0.26.3 (latest version)
In both cases I ran test.py and the OpenAI API returned the following completion (everything worked as expected):
[-0.01456643920391798, -0.00019150535808876157, 0.0035678150597959757,
-0.002183361677452922, -0.0118199922144413, 0.005178465507924557, -0.02064969204366207, -0.011248884722590446, -0.006718529388308525, -0.0322900116443634, 0.01849360205233097, 0.01343705877661705, -0.016196340322494507, -0.006872536148875952, 0.004013792145997286, -0.005172048695385456, 0.03131463751196861, -0.0071099624037742615, -0.005255468655377626, -0.006561314687132835, 0.014502270147204399, -0.004713237751275301, -0.005095045082271099, 0.012506603263318539, -0.0344204306602478, -0.020662525668740273, 0.008669277653098106, -0.02086786739528179, 0.009317387826740742, -0.009156964719295502, 0.01845510117...
test.py
import openai
openai.api_key = 'sk-xxxxxxxxxxxxxxxxxxxx'
def gpt3_embedding(content, engine='text-embedding-ada-002'):
#delay_print('Making a vector')
content = content.encode(encoding='ASCII',errors='ignore').decode()
response = openai.Embedding.create(input=content,model=engine)
vector = response['data'][0]['embedding'] # this is a normal list
#delay_print('Vector returned')
return vector
print(gpt3_embedding('Say this is a test'))
I'm trying data subscription feature of TDengine.
I tested its Python demo.
from taos.tmq import TaosConsumer
# Syntax: `consumer = TaosConsumer(*topics, **args)`
#
# Example:
consumer = TaosConsumer('topic1', 'topic2', td_connect_ip = "127.0.0.1", group_id = "local")
...
When executing the script, there is an error information:
ImportError: cannot import name 'TaosConsumer'
Did I miss some steps?
I think you need to update the version of taospy on your system - taospy is the TDengine connector for Python.
Try running pip install -U taospy to update it and then do your test again.
Make sure you're running Python 3.7 or later.
I am using a raspberry pi 4 mode B to interface communicate with a Teensy 4.0. I'm using ROS noetic on Ubuntu 20.04. I've flashed the code to the Teensy successfully using platformio. I have a problem, however, when I try and launch the calibration python script for the robot I'm working on. I'm interfacing the raspberry Pi with the Teensy through the GPIO pins (this is after I've flashed the code to the Teensy, I flashed it through usb). When I run the calibration script using roslaunch mini_ros spot_calibration I get the following error:
[servo_calibration-1] process has died [pid 4841, exit code 1, cmd /home/ubuntu/spark_ws/src/spot_mini_mini/mini_ros/src/servo_calibration __name:=servo_calibration __log:=/home/ubuntu/.ros/log/fa068172-32ea-11ec-b45a-513494152363/servo_calibration-1.log].
log file: /home/ubuntu/.ros/log/fa068172-32ea-11ec-b45a-513494152363/servo_calibration-1*.log
[ERROR] [1634874547.846356]: Mismatched protocol version in packet (b'\xf8'): lost sync or rosserial_python is from different ros release than the rosserial client
below is the python code in spot_calibration
#!/usr/bin/env python
"""
DESCRIPTION:
SUBSCRIBERS:
"""
from __future__ import division
import rospy
from mini_ros.srv import CalibServo, CalibServoResponse
from mini_ros.msg import JointPulse
import numpy as np
import sys
import rospkg
rospack = rospkg.RosPack()
sys.path.append(rospack.get_path('mini_ros') + '/../')
sys.path.append('../../')
class ServoCalibrator():
def __init__(self):
rospy.init_node('ServoCalibrator', anonymous=True)
self.serv = rospy.Service('servo_calibrator', CalibServo,
self.calib_service_cb)
self.jp_pub = rospy.Publisher('spot/pulse', JointPulse, queue_size=1)
def calib_service_cb(self, req):
""" Requests a servo to be moved to a certain position
Args: req
Returns: response
"""
try:
jp_msg = JointPulse()
jp_msg.servo_num = req.servo_num
jp_msg.servo_pulse = req.servo_pulse
self.jp_pub.publish(jp_msg)
response = "Servo Command Sent."
except rospy.ROSInterruptException:
response = "FAILED to send Servo Command"
return CalibServoResponse(response)
def main():
""" The main() function. """
srv_calib = ServoCalibrator()
rospy.loginfo(
"Use The servo_calibrator service (Pulse Width Unit is us (nominal ~500-2500))."
)
while not rospy.is_shutdown():
rospy.spin()
if __name__ == '__main__':
try:
main()
except rospy.ROSInterruptException:
pass
The package was supposedly made in ROS Melodic, so that might be why it's throwing the error, but I don't know what to change if the package is melodic exclusive.
The problem is indeed because the roslib package used by rosserial was build for Melodic. As you can guess this error is just caused because of mismatched version ids coming from the arduino side. The best option would be to rebuild ros_lib for Noetic.
To rebuild ros_lib all you have to do is navigate to your sketchbook and run make_libraries.py. Note that this will build up to the currently installed distro, so you need to run this on a machine that has Noetic installed.
cd <sketchbook>/libraries
rm -rf ros_lib
rosrun rosserial_arduino make_libraries.py .
If rebuilding isn't an option you can add the definitions manually. On the arduino side you'll have a ros_lib folder. You have two sub directories you need to change.
The first is ./ros/node_handle.h. At the top of the file you'll see a few protocol versions defined as const uint8_t. Add in the version id for noetic as const uint8_t PROTOCOL_VER6 = 0xfa; then change the line that states what version should be used. const uint8_t PROTOCOL_VER = PROTOCOL_VER6;.
Lastly, you just need to make this same change in ./ros_lib/ros/node_handle.h
import scapy.all as scapy
import requests
import json
This code work with API for getting information about venders
def vender_finding(mac_adr):
mac_url = 'http://macvendors.co/api/%s'
vender = (requests.get(mac_url % mac_adr))
response_dict = json.loads(json.dumps(vender.json()))
return response_dict['result']['company']
This code returns all devices connected to the network. result is something like this
the result of this code
def scan(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
This is the line which gives an error
answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
clents_list = []
for element in answered_list[1:]:
company = vender_finding(element[1].hwsrc)
clent_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc, "vender": company}
clents_list.append(clent_dict)
print(clents_list)
return clents_list
scan('192.168.1.0/24')
but now its return error like this.
In here now a new error starts to occur.
answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
This the error that I am getting.
raise ValueError("Unknown network interface %r" % name)
ValueError: Unknown network interface None
By installing the following software issue solved.
1.python 2.7.2 from python.org
2.Microsoft Visual C++ Compiler for Python 2.7 from https://www.microsoft.com/en-us/download/confirmation.aspx?id=44266.
(check this link for more. Microsoft Visual C++ 9.0 is required)
3.pip install scapy==2.4.3rc1 (this is recommended by StackOverflow contributor. this work very well.)
(check these link answer for a recommendation by user Cukic0d. GUID number of windows interface giving error: ValueError: Unknown network interface '{1619EEF1-4D71-4831-87AC-8E5DC3AA516A}')
4.winpcap (to perform scapy sniff() must install this)
Install python 2.7.2 and then install Microsoft Visual C++ Compiler for Python 2.7
You can try "iface" with your network interface.
Ex:
sendp(Ether()/IP(dst="1.2.3.4",ttl=(1,4)), iface="eth1")
More info: https://scapy.readthedocs.io/en/latest/usage.html
I am working on building a packet sniffing program using Python, however I have hit a speed bump. For some reason I think socket has not imported properly, because I am getting the following message when my program is run: AttributeError: module 'socket' has no attribute 'AF_PACKET'
I am using OS X and Pycharm is my IDE and I am running the latest version of Python if that helps.
Anyways here is my complete program so far:
import struct
import textwrap
import socket
def main():
connection = socket.socket(socket.AF_PACKET, socket.SOCKET_RAW, socket.ntohs(3))
while True:
rawData, address = connection.recvfrom(65535)
reciever_mac, sender_mac, ethernetProtocol, data = ethernet_frame(rawData)
print('\nEthernet Frame: ')
print('Destination: {}, Source: {}, Protocol: {}'.format(reciever_mac, sender_mac, ethernetProtocol))
# Unpack ethernet frame
def ethernet_frame(data):
reciever_mac, sender_mac, protocol = struct.unpack('! 6s 6s H', data[:14])
return getMacAddress(reciever_mac), getMacAddress(sender_mac), socket.htons(socket), data[14:]
# Convert the Mac address from the jumbled up form from above into human readable format
def getMacAddress(bytesAddress):
bytesString = map('{:02x}'.format, bytesAddress)
macAddress = ':'.join(bytesString).upper()
return macAddress
main()
Thanks for any help in advance!
Actually, AF_PACKET doesn't work on OS X, it works on Linux.
AF_PACKET equivalent under Mac OS X (Darwin)
I ran into this issue on macOS 10.13.1, using Python 3.6.3 and this cool scapy fork that is compatible with python3.
I was using version 0.22 of that tool and as suggested in this issue downgrading to version 0.21 fixed this issue!
In case scapy is not a viable alternative, you could also try the pcap library as suggested in this post (although using python 2 seems to be necessary here).