Why does printing a packed int freak out OS X? - python

When printing a binary packed nonce in the terminal, it generates a bunch of alerts.
The code of the program is:
from struct import pack, unpack
import hashlib
import sys
print "Input the message you want to work on:"
message = raw_input()
orig_hash = hashlib.sha512(message).digest()
trialValue = 99999999999999999999
target = 4103215547750
nonce = 0
while trialValue > target:
nonce += 1
packed_nonce = pack('>Q', nonce)
print packed_nonce
trialValue, = unpack('>Q',hashlib.sha512(packed_nonce + orig_hash).digest()[0:8])
print nonce
print trialValue
This isn't a big deal, but does anyone know why this happens?

Probably because some of the data you're printing contains a BEL (0x07) character, which causes the terminal to beep.
Don't print control characters unless you want the terminal to do weird things.

Related

How to repeat openeing tabs?

Here is my code:
times_to_repeat = 10
while times_to_repeat > 0:
import string
import random
S = 6
ran = ''.join(random.choices(string.ascii_lowercase + string.digits, k=S))
x = ran
print("The randomly generated string is : " + str(ran))
import webbrowser
webbrowser.open("prnt.sc/" + x)
times_to_repeat -= 1
I'm trying to do the prnt.sc challenge, and I want to be able to open 10 tabs of random strings, to speed up the process. My problem is that it only opens one tab when I run it, but it prints my random string ten times. Both are on a loop, so shouldn't both things repeat? I get "your random string is (whatever the string is) 10 times, but my browser only opens 1 tab. I'm quite new to python so I don't know a whole lot about loops.
Currently, your code seems to be opening 10 different browsers.
I'm not absolutely sure about how but seems that the internal call of webbrowser.open("prnt.sc/" + x) is making the OS don't be able to use the currently active browser, since prnt.sc/ is not a web URL, because the https:// part is missing.
Just add the protocol and it will work:
while times_to_repeat > 0:
import string
import random
S = 6
ran = ''.join(random.choices(string.ascii_lowercase + string.digits, k=S))
x = ran
print("The randomly generated string is : " + str(ran))
import webbrowser
webbrowser.open("https://prnt.sc/" + x)
times_to_repeat -= 1
Nevertheless, your code loop is a bit strange and a bit difficult to read. Also, importing libraries on a while loop is not a really good practice.
import string
import random
import webbrowser
S = 6
times_to_repeat = 4
for x in range(0, times_to_repeat):
ran = ''.join(random.sample(string.ascii_lowercase, S))
print("The randomly generated string is : " + str(ran))
webbrowser.open("https://prnt.sc/" + ran)

Python using """ some data """ without printing newline

So what im trying to do is printing several data with """ """ my Question is if its possible that i can hold this without python printing it again and again im using the sys.stdout.write func with "\r" at the end but in the Console its still moving down. Does Somebody have an idea how to it with """ """ or another method?(Im using Python 2.7)
Thats not really what i want i want the stuff thats in the """ """ to be not moving in the console so that its not printed every time again want to stay in one place like this and not like this
In python 2 you can simply add comma to end of the statement to avoid adding "\n" to output.
print "Hello",
print "world",
The output will be Hello world.
Update:
Look here to read about escape codes.
Made a simple example for you:
import time
template = """
Line 1: [%d]
Line 2: [%d]
"""
prev_line_char = "\033[F"
k = 3
m = 4
while True:
print template % (k, m)
k += 1
m += 3
time.sleep(1)
for i in range(4):
print prev_line_char,

Test condition not work

I'm using python with select and system library here the code :
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from select import select
import sys
def main():
timeout = 5
print('Please type something: ', end = '')
sys.stdout.flush()
rlist, wlist, xlist = select([sys.stdin],[],[], timeout)
k=sys.stdin.readline()
if k=="f":
data = sys.stdin.readline()
print('you entered', data)
else:
print('\nSorry, {} seconds timeout expired!'.format(timeout))
print(k) #see the sys.stdin result
if __name__ == '__main__':
main()
this program wait the user until put a char
i put in the program a condition if the user put a char after 5 second so the program stop also if the user give something different of the 'f' char but the problem the condition doesn't work i put a test to see the result of the sys.stdin value he give me the 'f char but when i put the result in the if statement the program don't work
this screenshot of the result:
enter image description here
Can someone give me the reason of this result ?
I don't know much about the select library. But here is an error the immediately caught my eyes.
You read from the input with k=sys.stdin.readline(). This means that k will contain the complete line, including the \n (newline) symbol. So if you press f + Enter the value of k will be "f\n", not "f". This is the reason why the comparison is always wrong.
It would be best to compare the values with if k.strip() == "f":.
Edit
Just had a quick look into the select library. If you want to determine if a timeout happened, you need to work with the return values of the select function. And not read from input directly. Otherwise you will wait regardless if a timeout happened or not.
I'm not sure what you want to accomplish, but something similar to the following code will work.
from __future__ import print_function
from select import select
import sys
timeout = 5
print('Please type something: ', end = '')
sys.stdout.flush()
inputready, _, _ = select([sys.stdin],[],[], timeout)
if inputready:
k = sys.stdin.readline()
if k.strip()=="f":
print("You printed 'f'")
else:
print("Not 'f'")
else:
print('\nSorry, {} seconds timeout expired!'.format(timeout))

Arduino to Python - is serial input from readline() an integer or an actual string?

So I'm sending a bunch of serial data from my Arduino 2560 Mega to my Python program, where I will be acting on integer data only. Initially, my Arduino calibrates a bunch of things, serially-printing confirmation information...then it starts to take temperature values from an LM35. Those temperature values then get serially printed.
I either:
a) Want to know how to use Python's readline() function when an integer is received starting when the temperature readings start getting printed serially.
OR
b) Test the incoming string from readline() from the start, determining when the numbers I care about start getting received.
And yes, treat these temperature values as integers not floats.
Right now, here's what I'm doing:
while(1==1):
if (s.inWaiting() > 0):
myData = s.readline()
time = myData
value = int(time.strip('\0'))
if (time.isDigit()):
# do stuff
I receive the error:
value = int(time.strip('\0'))
ValueError: invalid literal for int() with base 10: 'Obtaining color values for: Saline/Air\r\n'
Which makes sense because the string literal 'Obtaining color values for:Saline/Air\r\n', even after stripping, would never convert via the int() function.
Also let me know if .isDigit() is even necessary (or for that matter, being used correctly). I just started working with Python a couple weeks ago so it's all up in the air from my perspective.
You can do the following to convert a string to an integer:
while(1==1):
if (s.inWaiting() > 0):
myData = s.readline()
try:
# This will make it an integer, if the string is not an integer it will throw an error
myData = int(myData)
except ValueError: # this deals will the error
pass # if we don't change the value of myData it stays a string
Example
Here is an example you can try.
In Python:
import serial
# Converts to an integer if it is an integer, or it returns it as a string
def try_parse_int(s):
try:
return int(s)
except ValueError:
return s
ser = serial.Serial('/dev/ttyACM0', 115200)
while True:
data = ser.readline().decode("utf-8").strip('\n').strip('\r') # remove newline and carriage return characters
print("We got: '{}'".format(data))
data = try_parse_int(data)
print(type(data))
On my Arduino:
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println(1);
delay(1000);
Serial.println("test");
delay(1000);
}
This will produce:
We got: 'test'
<class 'str'>
We got: '1'
<class 'int'>
You should catch the exception.
while True:
if s.inWaiting() > 0:
myData = s.readline()
try:
value = int(mydata.strip('\0'))
except ValueError:
# handle string data (in mydata)
else:
# handle temperature reading (in value)
So if the value can be converted to an int, the else block runs. If the value is a string, the except block runs.

Converting a bytearray from a serial port to a float

I am writing a python script that will communicate to a Fluke meter over a COM port. I am able to receive the data but want to parse it into a usable float. The code looks like this:
import serial
ser = serial.Serial('COM3', 115200, timeout=1)
#Decalring some variables
FlukeID = b'ID\r'
FlukeQM = b'QM\r'
#Requesting the meters ID to verify connection on terminal
ser.writelines(FlukeID)
line = ser.readline()
print(line)
#Declaring variables for my while loop
thermdata = 0
t=1
ser.writelines(FlukeQM)
thermdata = ser.readline()
while(t < 5):
ser.writelines(FlukeQM)
#thermdata = (thermdata + ser.readline()) /2
thermdata = ser.readline()
print(thermdata)
t+=1
The data returned by the device looks like this on the console:
8.597E3,OHM,NORMAL,NONE INCORRECT
EDIT: The data actually appears like this over the terminal:
b'0\r8.597E3,OHM,NORMAL,NONE\r'
I just want to be able to use the numerical value at the beginning so I can do some calculations over time. I also need to be able to use the scientific notion portion in my number as I will not know the range of my measurements before hand. I know there must be a simple way to do this and would greatly appreciate any help.
On a side note, I would also like to be able to graph these values or place them into some kind of .csv file. If you have any comments on where to look to learn how to do this also that would be great, but I am mostly concerned with the handling of the bytearray.
Use split() to break your string into the comma separated parts. Then the first part is the string '8.597E3', which you convert using the float() function.
s = '8.597E3,OHM,NORMAL,NONE'.split(',')
value = float(s[0])
How about something like:
def atof(text):
try:
return float(text)
except ValueError:
return text
thermdata = b'0\r8.597E3,OHM,NORMAL,NONE\r'
for line in thermdata.strip().split(b'\r'):
print(list(map(atof, line.split(b','))))
# [0.0]
# [8597.0, b'OHM', b'NORMAL', b'NONE']

Categories