I collect all the data to parameter the Serial Connexion through User Input.
However Pyserial API doesnt take for exemple the value "EIGHTBITS" directly as parameter but you have to call serial.EIGHTBITS.
Is there a way to over come this ?
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--Port", required=True,
help="specify Port Name")
ap.add_argument("-b", "--Baud", type=int,required=True,
help="Specify Baud rate")
ap.add_argument("-t", "--timeout", type=float,required=True,
help="Connexion Timeout")
ap.add_argument("-d", "--ByteSize",default="EIGHTBITS",choices=['FIVEBITS','SIXBITS','SEVENBITS','EIGHTBITS'],
help="Specify the Data bits number")
ap.add_argument("-s", "--StopBits", default="STOPBITS_ONE",choices=['STOPBITS_ONE','STOPBITS_ONE_POINT_FIVE','STOPBITS_TWO'],
help="StopBits Value")
ap.add_argument("-pa", "--parity", default="PARITY_NONE",choices=['PARITY_NONE','PARITY_EVEN','PARITY_ODD','PARITY_MARK','PARITY_SPACE'],
help="Set up the Parity Bit")
ap.add_argument("-f", "--FlowControl", type=bool, default=False,
help="StopBits Value")
args = vars(ap.parse_args())
Port = args["Port"]
BaudRate = args["Baud"]
Timeout = args["timeout"]
ByteSize = args["ByteSize"]
Stop = args["StopBits"]
Parity = args["parity"]
FlowC=args["FlowControl"]
ser=serial.Serial(Port,BaudRate,bytesize=ByteSize,parity=Parity,stopbits=Stop,timeout=Timeout,xonxoff=FlowChart)
Use getattr to retrieve the value of serial.EIGHTBITS etc from the serial module, by name (string), eg. "EIGHTBITS".
Parity = getattr(serial, args["parity"])
Related
I want to capture the limited number of packet. for example, while I am using the command python python.py -I eth0 -c 10 then I wan to capture only 10 number of packet and exit but I am printing many packets instead of 10. please tell me where am I wrong.
#!/usr/bin/python
import argparse
import pyshark
import time
import re as regex
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--interface', metavar=" ", type=str, required = True, help = 'To specify the interface ')
parser.add_argument('-v', '--verbose', required = False, action = 'store_true', help = 'To print the all layer of packet')
parser.add_argument('-o', '--output', metavar=' ', help = 'To capture and save the pcap in a file')
parser.add_argument('-p', '--protocol', metavar=' ', help= 'To capture packet using ptotocl filter')
parser.add_argument('-u', '--udp', action = 'store_true', help = 'To capture udp packet only')
parser.add_argument('-t', '--tcp', action = 'store_true', help = 'To capture tcp packet only')
parser.add_argument('-c', '--count', metavar=' ',type=int, default=1, help = 'To capture limited number of packet')
args = parser.parse_args()
if args.count:
capture = pyshark.LiveCapture(interface=args.interface)
capture.sniff(packet_count = args.count)
elif args.protocol:
capture = pyshark.LiveCapture(interface=args.interface, display_filter=args.protocol)
elif args.udp:
capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='udp')
elif args.tcp:
capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='tcp')
else:
capture = pyshark.LiveCapture(interface=args.interface, output_file=args.output)
# capture.sniff(packet_count = args.count)
packet_list = []
for packet in capture.sniff_continuously():
if 'IP Layer' in str(packet.layers):
protocol = regex.search(r'(Protocol:)(.*)',str(packet.ip))
protocol_type = protocol.group(2).strip().split(' ')[0]
# proto = protocol_type
localtime = time.asctime(time.localtime(time.time()))
proto = protocol_type
src_addr = packet.ip.src
dst_addr = packet.ip.dst
length = packet.length
print (localtime, '\t' , proto, '\t' ,src_addr, '\t', dst_addr, '\t' , length)
if args.verbose:
print(packet.show())
output
I am capturing more than 10 packets.
capture.sniff(packet_count = args.count)
This will immediately read the given number of packets
for packet in capture.sniff_continuously():
This will read packets without any limit.
So if you want to only read the number of packets don't immediately call sniff when parsing the args.count argument but instead apply packet_count = args.count later to sniff_continously:
for packet in capture.sniff_continuously(packet_count = args.count):
I want to capture the limited number of packet. for example, while I am using the command python python.py -I eth0 -c 10 then I wan to capture only 10 number of packet and exit but I am getting error.the below are the code and erro I am getting.
!/usr/bin/python
import argparse
import pyshark
import time
import re as regex
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--interface', metavar=" ", type=str, required = True, help = 'To specify the interface ')
parser.add_argument('-v', '--verbose', required = False, action = 'store_true', help = 'To print the all layer of packet')
parser.add_argument('-o', '--output', metavar=' ', help = 'To capture and save the pcap in a file')
parser.add_argument('-p', '--protocol', metavar=' ', help= 'To capture packet using ptotocl filter')
parser.add_argument('-u', '--udp', action = 'store_true', help = 'To capture udp packet only')
parser.add_argument('-t', '--tcp', action = 'store_true', help = 'To capture tcp packet only')
parser.add_argument('-c', '--count', metavar=' ',default=1, help = 'To capture limited number of packet')
args = parser.parse_args()
if args.protocol:
capture = pyshark.LiveCapture(interface=args.interface, display_filter=args.protocol)
elif args.udp:
capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='udp')
elif args.tcp:
capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='tcp')
else:
capture = pyshark.LiveCapture(interface=args.interface, output_file=args.output)
capture.sniff(packet_count = args.count)
packet_list = []
for packet in capture.sniff_continuously():
if 'IP Layer' in str(packet.layers):
protocol = regex.search(r'(Protocol:)(.*)',str(packet.ip))
protocol_type = protocol.group(2).strip().split(' ')[0]
# proto = protocol_type
localtime = time.asctime(time.localtime(time.time()))
proto = protocol_type
src_addr = packet.ip.src
dst_addr = packet.ip.dst
length = packet.length
print (localtime, '\t' , proto, '\t' ,src_addr, '\t', dst_addr, '\t' , length)
if args.verbose:
print(packet.show())
error
python python.py -i eth0 -c 10
Traceback (most recent call last):
File "/home/kali/python.py", line 32, in <module>
capture.sniff(packet_count = args.count)
File "/home/kali/.local/lib/python3.10/site-packages/pyshark/capture/capture.py", line 144, in load_packets
self.apply_on_packets(
File "/home/kali/.local/lib/python3.10/site-packages/pyshark/capture/capture.py", line 256, in apply_on_packets
return self.eventloop.run_until_complete(coro)
File "/usr/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
return future.result()
File "/home/kali/.local/lib/python3.10/site-packages/pyshark/capture/capture.py", line 267, in packets_from_tshark
await self._go_through_packets_from_fd(tshark_process.stdout, packet_callback, packet_count=packet_count)
File "/home/kali/.local/lib/python3.10/site-packages/pyshark/capture/capture.py", line 299, in _go_through_packets_from_fd
if packet_count and packets_captured >= packet_count:
TypeError: '>=' not supported between instances of 'int' and 'str'
File "/home/kali/.local/lib/python3.10/site-packages/pyshark/capture/capture.py", line 299, in _go_through_packets_from_fd
if packet_count and packets_captured >= packet_count:
TypeError: '>=' not supported between instances of 'int' and 'str'
It is expected that packet_count is an integer. But packet count is taken from the command line (args) and thus is as string unless explicitly given otherwise:
parser.add_argument('-c', '--count', metavar=' ',default=1, help = 'To capture limited number of packet')
...
capture.sniff(packet_count = args.count)
To fix this args.count either must be converted to int explicitly or the proper type should be given when parsing the args with the type argument:
parser.add_argument('-c', '--count', type=int, metavar=' ', default=1, help = 'To capture limited number of packet')
I am using while loop with argparse in python and it is as below.
parser.add_argument('-x', '--height', help='Height of the box')
parser.add_argument('-l', '--length', type=int, help='Length of the box')
parser.add_argument('-b', '--breadth', type=int, help='Breadth of the box')
exitcode = "stop"
args = ""
while args != exitcode:
args = parser.parse_args(input("enter text: ").split())
print (args.height)
when the user enters stop i want the program to exit.
but in this it is showing an error as below
error: unrecognized arguments: stop
how can i exit this with the stop
In argparse you can define Action classes that can be used to perform specific logic once an argument was passed.
Here's a code which performs exit once --stop is passed.
from argparse import ArgumentParser, Action
class StopAction(Action):
def __call__(self, parser, namespace, values, option_string=None):
# Do whatever actions you want
if values:
print("Exiting")
exit(0)
arg_parser = ArgumentParser()
arg_parser.add_argument('-x', '--height', help='Height of the box')
arg_parser.add_argument('-l', '--length', type=int, help='Length of the box')
arg_parser.add_argument('-b', '--breadth', type=int, help='Breadth of the box')
arg_parser.add_argument('stop', nargs='?', action=StopAction, default=False)
while True:
arg_parser.parse_args(input("enter text: ").split())
When executed it looks like this:
± % python test.py
enter text: -x 1
enter text: -x 2
enter text: stop
Exiting
Check input before parsing may be a solution:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-x', '--height', help='Height of the box')
parser.add_argument('-l', '--length', type=int, help='Length of the box')
parser.add_argument('-b', '--breadth', type=int, help='Breadth of the box')
while True:
text = input("enter text: ")
if text != "stop":
args = parser.parse_args(text.split())
print(args.height)
else:
print("Stop")
break
Test run:
enter text: -x 1
1
enter text: -x 2
2
enter text: -l 1
None
enter text: -b 1
None
enter text: -x 1 -l 1 -b 1
1
enter text: stop
Stop
The vosk model that I'm using is the vosk-model-en-us-aspire-0.2 (1.4GB). Every time needs quite an amount of time to load the vosk model. Is it necessary to recreate the vosk object every time? It takes much time to load the model if we only load the model once. It can save up at least half of the time.
No it isn't required. In many of the examples they load the model first and then perform transcription. Your software is probably just not written correctly.
https://github.com/alphacep/vosk-server/blob/master/websocket-microphone/asr_server_microphone.py
#!/usr/bin/env python3
import json
import os
import sys
import asyncio
import websockets
import logging
import sounddevice as sd
import argparse
import queue
from vosk import Model, KaldiRecognizer
def int_or_str(text):
"""Helper function for argument parsing."""
try:
return int(text)
except ValueError:
return text
def callback(indata, frames, time, status):
"""This is called (from a separate thread) for each audio block."""
loop.call_soon_threadsafe(audio_queue.put_nowait, bytes(indata))
async def serve_client(websocket, path):
clients.add(websocket)
print ("Client connected from", websocket)
await websocket.wait_closed()
clients.remove(websocket)
async def recognize_microphone():
global audio_queue
model = Model(args.model)
audio_queue = asyncio.Queue()
with sd.RawInputStream(samplerate=args.samplerate, blocksize = 2000, device=args.device, dtype='int16',
channels=1, callback=callback) as device:
logging.info("Running recognition")
rec = KaldiRecognizer(model, device.samplerate)
while True:
data = await audio_queue.get()
if rec.AcceptWaveform(data):
result = rec.Result()
logging.info(result)
websockets.broadcast(clients, result)
async def main():
global args
global clients
global loop
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-l', '--list-devices', action='store_true',
help='show list of audio devices and exit')
args, remaining = parser.parse_known_args()
if args.list_devices:
print(sd.query_devices())
parser.exit(0)
parser = argparse.ArgumentParser(description="ASR Server",
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[parser])
parser.add_argument('-m', '--model', type=str, metavar='MODEL_PATH',
help='Path to the model', default='model')
parser.add_argument('-i', '--interface', type=str, metavar='INTERFACE',
help='Bind interface', default='0.0.0.0')
parser.add_argument('-p', '--port', type=int, metavar='PORT',
help='Port', default=2700)
parser.add_argument('-d', '--device', type=int_or_str,
help='input device (numeric ID or substring)')
parser.add_argument('-r', '--samplerate', type=int, help='sampling rate', default=16000)
args = parser.parse_args(remaining)
logging.basicConfig(level=logging.INFO)
loop = asyncio.get_running_loop()
clients = set()
logging.info("Listening on %s:%d", args.interface, args.port)
await asyncio.gather(
websockets.serve(serve_client, args.interface, args.port),
recognize_microphone())
if __name__ == '__main__':
asyncio.run(main())
I found a Python script to list all Vcenter VM attributes, but now I need to register some of attributes into a Python list (or array, dict... ).
But it doesn't works.
My getVminfos.py :
EDIT : the right file :
import argparse
import atexit
import itertools
import unicodedata
import pyVmomi
from pyVmomi import vmodl
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
def GetArgs():
parser = argparse.ArgumentParser(description='Process args for retrieving all the Virtual Machines')
parser.add_argument('-s', '--host', required=True, action='store',help='Remote host to connect to')
parser.add_argument('-o', '--port', type=int, default=443, action='store',help='Port to connect on')
parser.add_argument('-u', '--user', required=True, action='store',help='User name to use when connecting to host')
parser.add_argument('-p', '--password', required=False, action='store',help='Password to use when connecting to host')
args = parser.parse_args()
return args
def print_vm_info(virtual_machine):
"""
Print information for a particular virtual machine or recurse into a
folder with depth protection
"""
Ansible_Hosts = []
Ansible_Groups = []
Ansible_Names = []
summary = virtual_machine.summary
print("Name : ", summary.config.name)
print("Template : ", summary.config.template)
#print("Path : ", summary.config.vmPathName)
print"Guest : ", str(unicodedata.normalize('NFKD', summary.config.guestFullName))
#print("Instance UUID : ", summary.config.instanceUuid)
#print("Bios UUID : ", summary.config.uuid)
print"State : ", summary.runtime.powerState
if summary.guest is not None:
ip_address = summary.guest.ipAddress
if ip_address:
Ansible_Hosts.append([ip_address])
print "Ansible_Hosts[1:15]", Ansible_Hosts[1:15]
def main():
args = GetArgs()
try:
si = SmartConnect(host=args.host,user=args.user,pwd=args.password,port=int(args.port))
if not si:
print("Could not connect to the specified host using specified "
"username and password")
return -1
atexit.register(Disconnect, si)
content = si.RetrieveContent() # get root folder
container = content.rootFolder # starting point to look into
viewType = [vim.VirtualMachine] # object types to look for
recursive = True # whether we should look into it recursively
containerView = content.viewManager.CreateContainerView(
container, viewType, recursive)
children = containerView.view
for child in children:
print_vm_info(child)
except vmodl.MethodFault as error:
print("Caught vmodl fault : " + error.msg)
return -1
return 0
# Start program
if __name__ == "__main__":
main()
Prints works like a charm, but always my lists (Ansible_Hosts, ...) are empty...
The lists initialization statements (Ansible_Hosts = [] etc.) should go to main()