I'm trying to to capture a screenshot of an Agilent scope in python but using read_raw give me an issue “print cancel” can you please help
`import pyvisa as visa
import sys
#
# Example VISA address for a USB connection:
VISA_ADDRESS = 'USB0::0x2A8D::0x1797::CN57046145::0::INSTR'
# Define VISA Resource Manager
scope = visa.ResourceManager('C:\\Windows\\System32\\visa32.dll')
scope.read_termination = '\n'
scope.write_termination = '\n' #or = '\r'
print (scope.query('*IDN?\n'))
scope.write('SAVE:IMAG:FILEF PNG')
scope.write(':HARDcopy: STARt')
raw_data = scope.read_raw ()
f= open ('Shot.png' 'wb')
f.write (raw_data)
f.close `
import sys
import time
import pyvisa as visa # PyVISA library
class SCOPE_MSO_S_104A:
def __init__(self, address):
self.rm = visa.ResourceManager(r'C:\WINDOWS\system32\visa64.dll')
self.scope = self.rm.open_resource(address)
self.scope.timeout = 10000 # 10s
self.scope.write_termination = '\n'
self.scope.read_termination = '\n'
print('MSO S 104A ID string:\n ', self.scope.query('*IDN?'), flush=True)
self.scope.query('*RST;*OPC?')
def getPng(self, file):
time.sleep(1)
data = self.scope.query_binary_values(':DISPlay:DATA? PNG,SCReen,1,NORMal', datatype='B', header_fmt='ieee', container=bytes)
file_id = open(file, 'wb')
file_id.write(data)
file_id.close()
def closeScope(self):
self.scope.close()
scope = SCOPE_MSO_S_104A('USB0::0x2A8D::0x9050::MY55160105::0::INSTR')
scope.getPng('newPng.png')
from IPython.display import Image
Image('newPng.png')
Related
I have a list of IP addresses like 1000 no's. I am reading the ip_file.txt and storing the result file as result_date.txt. Below is the code that I achieved the result. But my issue is it's taking too long to execute the entire files. Can anyone suggest multithreading, please so that the desired result can be achieved quickly? Thanks in advance.
#!/usr/bin/env python
import os
import csv
import paramiko
from datetime import datetime
import time
import sys
import re
from collections import defaultdict
# Verifies your os type
from paramiko import file
OS_TYPE = os.name
# Sets the count modifier to the os type
count = '-n' if OS_TYPE == 'nt' else '-c'
def create_ip_list():
ip_list = []
with open("ip_file.txt", "r") as file:
for line in file:
ip_list.append(line.strip())
return ip_list
# fetching data
now = datetime.now()
dat = now.strftime("%d/%m/%Y")
# time = now.strftime("%H:%M:%S")
date_string = dat.replace('/', '-')
timestr = time.strftime("%d%m%Y-%H%M%S")
def ping_device(ip_list):
"""Ping ip_list and return results
return: None
rtype: None
"""
results_file = open("results_" + str(timestr) + ".txt", "w")
for ip in ip_list:
response = os.popen(f"ping {ip} {count} 1").read()
time.sleep(1.5)
#fetch Average time
print(response)
for i in response.split("\n"):
para = i.split("=")
try:
if para[0].strip() == "Minimum":
latency = para[3].strip()
print(latency)
# output1=latency[0:8].split(" ")
# test=output1[0]
# print(test)
except:
print("time run")
if "Received = 1" and "Approximate" in response:
#print(f"UP {ip} Ping Successful")
results_file.write(f"{ip},UP,{latency}" + "\n")
else:
print(f"Down {ip} Ping Unsuccessful")
results_file.write(f"{ip} Down" + "\n")
results_file.close()
if __name__ == "__main__":
ping_device(create_ip_list())
Write a function ping_one_device that takes a single ip and returns a single string giving the status. It should be easy to pull this out of ping_device.
Then
with open(results_file, "w") as results_file:
with ThreadPoolExecutor() as executor:
for result in map(ping_one_device, ip_list):
results_file.write(result)
im beginner and i have tried for a lot
code :
conn = netmiko.ConnectHandler(ip='10.254.60.10', device_type='cisco_ios',
username='user', password='P#ssw0rd')
print (conn.send_command('show interface Ethernet0/0 | i line|Des|Int'))
output like this
Ethernet0/0 is up, line protocol is up
Description: CUSTOMER A
Internet address is 10.254.60.69/30
how to auto ping to IP PtP using conn.send_command() based on result of show interface command?
example ping to 10.254.60.70
You get text
text = '''Ethernet0/0 is up, line protocol is up Description: CUSTOMER A
Internet address is 10.254.60.70/30'''
and you can get IP/MASK using string functions
address = text.split(' ')[-1]
print(address) # 10.254.60.70/30
and then you can use standard module ipaddress
import ipaddress
net = ipaddress.ip_interface(address)
ip = str(net.network.broadcast_address)
print( ip ) # 10.254.60.71
or not standard module netaddr
import netaddr
net = netaddr.IPNetwork(address)
ip = str(net.broadcast)
print( ip ) # 10.254.60.71
EDIT: Minimal working code
text = '''Ethernet0/0 is up, line protocol is up Description: CUSTOMER A
Internet address is 10.254.60.69/30'''
address = text.split(' ')[-1]
print(address) # 10.254.60.69/30
print('\n--- ipaddress ---\n')
import ipaddress
net = ipaddress.ip_interface(address)
print('ip :', net.ip ) # 10.254.60.69
print('ip+1:', net.ip+1 ) # 10.254.60.70
print('ip-1:', net.ip-1 ) # 10.254.60.68
#bip = net.network.broadcast_address
bip = str(net.network.broadcast_address)
print('bip :', bip ) # 10.254.60.71
print('\n--- netaddr ---\n')
import netaddr
net = netaddr.IPNetwork(address)
print('ip :', net.ip ) # 10.254.60.69
print('ip+1:', net.ip+1 ) # 10.254.60.70
print('ip-1:', net.ip-1 ) # 10.254.60.68
bip = net.broadcast
#bip = str(net.broadcast)
print('bip :', bip ) # 10.254.60.71
Result:
10.254.60.69/30
--- ipaddress ---
ip : 10.254.60.69
ip+1: 10.254.60.70
ip-1: 10.254.60.68
bip : 10.254.60.71
--- netaddr ---
ip : 10.254.60.69
ip+1: 10.254.60.70
ip-1: 10.254.60.68
bip : 10.254.60.71
This could be your sample and so easy minimal code with Netmiko :
from netmiko import ConnectHandler
cisco_Router = {
"device_type": "cisco_ios",
"host": "your_router_ip",
"username": "your_username",
"password": "your_password"}
with ConnectHandler(**cisco_Router) as net_connect:
result = net_connect.send_command("ping 4.2.2.4")
net_connect.disconnect()
print(result)
I haven't write it for netmiko yet, but I often use this code for paramiko.
import threading
from ping3 import ping
from queue import Queue
from ipaddress import ip_network, ip_address
import paramiko
import time
from termcolor import colored
import sys
import os
import subprocess
file1 = open('PING_OK.txt', 'w')
file2 = open('PING_NOK.txt', 'w')
hosts=[]
f1 = open('hostfile.txt', 'r')
devices= f1.readlines()
#print(devices)
for i in devices:
i = i.split()
hosts.append(i[0])
hosts_live = []
q = Queue()
for host in hosts:
q.put(host)
enter = "\r\n"
def ping2(ip_address):
from pythonping import ping
output = ping(ip_address, verbose=True)
output_list =output.rtt_avg_ms
print(output_list)
if output_list == 2000:
print("erişim yok"+ip_address)
file2.write(ip_address+"\n")
else:
print ("erişim var"+ip_address)
file1.write(ip_address + "\n")
def worker():
while True:
host = q.get()
ping2(host)
time.sleep(2)
q.task_done()
for i in range(1):#aynı anda bağlantı 15 ten fazla girilmemeli #
t = threading.Thread(target=worker)
t.deamon = True
t.start()
q.join()
file1.close()
file2.close()
Basically, I have my code, which finds the Lobby ID of a video-game, which then sends to my laptop. This then opens the exe with a argument and that certain Lobby ID. I want it to change when I start up another game/server. I have the script to output when the lobby ID changes, but when I plug it into my socket script. It only outputs the first one.
If I hash out all the s= socket... part and under it functions correctly
import socket
import glob
import os
import re
placeholder = ''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.0.17'
port = 50502
s.connect((host,port))
while True:
GAME_DIRECTORY = 'C:/Program Files/Oculus/Software/Software/ready-at-dawn-echo-arena'
logs = glob.glob(GAME_DIRECTORY + '/_local/r14logs/*')
log = max(logs, key = os.path.getctime)
with open(log, 'r') as f:
file = f.read()
lobbyid = re.findall(r'........-....-....-....-............', file)[-1]
if lobbyid != placeholder:
if lobbyid != ('00000000-0000-0000-0000-000000000000'):
placeholder = lobbyid
print (lobbyid)
def ts(str):
s.send(lobbyid.encode())
data = ''
data = s.recv(1024).decode()
s.close ()
ts(s)
I am trying to make use of VLC python module to play files after reading them into memory. I have the following code that reads a valid video file into the memory. I need to now play the video directly from the memory.
import vlc
File1 = open('vid.webm','rb')
Axel = File1.read()
Now i need to play the contents in Axel, how can I do this.
You can refer to the code below.
# -*- coding: utf-8 -*-
import ctypes
import io
import sys
import time
import vlc
MediaOpenCb = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_uint64))
MediaReadCb = ctypes.CFUNCTYPE(ctypes.c_ssize_t, ctypes.c_void_p, ctypes.POINTER(ctypes.c_char), ctypes.c_size_t)
MediaSeekCb = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.c_uint64)
MediaCloseCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)
def media_open_cb(opaque, data_pointer, size_pointer):
data_pointer.contents.value = opaque
size_pointer.contents.value = sys.maxsize
return 0
def media_read_cb(opaque, buffer, length):
stream=ctypes.cast(opaque,ctypes.POINTER(ctypes.py_object)).contents.value
new_data = stream.read(length)
for i in range(len(new_data)):
buffer[i]=new_data[i]
return len(new_data)
def media_seek_cb(opaque, offset):
stream=ctypes.cast(opaque,ctypes.POINTER(ctypes.py_object)).contents.value
stream.seek(offset)
return 0
def media_close_cb(opaque):
stream=ctypes.cast(opaque,ctypes.POINTER(ctypes.py_object)).contents.value
stream.close()
callbacks = {
'open': MediaOpenCb(media_open_cb),
'read': MediaReadCb(media_read_cb),
'seek': MediaSeekCb(media_seek_cb),
'close': MediaCloseCb(media_close_cb)
}
def MediaPlayerTimeChanged(event, userData):
print event.u.new_time
def main(stream):
instance = vlc.Instance()
player = instance.media_player_new()
vlc_events = player.event_manager()
vlc_events.event_attach(vlc.EventType.MediaPlayerTimeChanged, MediaPlayerTimeChanged, None)
media = instance.media_new_callbacks(callbacks['open'], callbacks['read'], callbacks['seek'], callbacks['close'], ctypes.cast(ctypes.pointer(ctypes.py_object(stream)), ctypes.c_void_p))
player.set_media(media)
player.play()
while True:
time.sleep(1)
if __name__ == '__main__':
try:
path = "d:/1.mp4"
stream = open(path, 'rb')
main(stream)
except IndexError:
print('Usage: {0} <path>'.format(__file__))
sys.exit(1)
I have two BBC Micro Bit and using Radio function to transfer data from one slave to the master Micro Bit. When the data is transferred I am getting random carriage returns, I am not sure what is the problem, I have tried to strip any random CR etc, but still getting the same problem.
a=1,On,
12
=2,
Off, 77
=3,
On, 88
===================================================
Gateway code
from microbit import *
import radio
radio.config(group=0)
radio.on()
while True:
incoming = radio.receive()
if incoming:
uart.write(incoming)
==============================================
Slave code
from microbit import *
import radio
radio.config(group=0)
radio.on()
while True:
if button_a.was_pressed():
radio.send('Matt,A=On,Off' + '\n') # a-ha
display.scroll("A")
if button_b.was_pressed():
radio.send('Matt,B=On,Off' + '\n') # a-ha
display.scroll("B")
=========================================================
PySerial code
import sys
import glob
import serial
def serial_ports():
ports = ['COM%s' % (i + 1) for i in range(256)]
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
if __name__ == '__main__':
print(serial_ports())
try:
ser = serial.Serial('COM5', 115200, timeout = 0)
print("connected to: " + (ser.portstr))
except serial.SerialException:
pass
while True:
line = ser.readline().decode('utf-8')
# Read a line and convert it from b'xxx\r\n' to xxx
if line: # If it isn't a blank line
f = open('output.csv', 'a+')
f.write(line + '\n')
print(line)
f.close()
ser.close()
I found your scripts worked without sending extra carriage returns. I tested using two microbits. I used the REPL in mu and also CoolTerm, set to 115200 baud. I am using Linux Mint as my OS.
CoolTerm output:
Matt,B=On,Off
Matt,A=On,Off
Added after the pyserial code was posted:
The code below works for me to produce the expected output without extra blank lines. The newline is removed by using the end='' in the print statement. Finding the microbit using the pid and vid enables you to have other serial devices attached. Credit to microbit-playground for posting example code on how to use pid and vid to find the microbit.
I tested this on Linux using the jupyter notebook. It should work on Windows without modification.
import serial
import serial.tools.list_ports as list_ports
def find_microbit_comport():
ports = list(list_ports.comports())
for p in ports:
if (p.pid == 516) and (p.vid == 3368):
return str(p.device)
if __name__ == '__main__':
ser = serial.Serial()
ser.baudrate = 115200
ser.port = find_microbit_comport()
ser.open()
while True:
line = ser.readline().decode('utf-8')
if line: # If it isn't a blank line
f = open('output.csv', 'a+')
f.write(line)
print(line, end='')
f.close()
ser.close()