How do I find the last sector of harddisk? - python

I have not tried to find the last sector by multiplying the number of sectors by 10. I tried to find it by increasing 1 but the system was very tired and took a lot of time. I don't want to filter out the output of ready commands.
How can I find the number of cylinders, heads and sectors. I think I will get the number of sectors by converting from chs system to lba system.
import os
def main():
s=1
if os.name == "nt":
while True:
if read_sector(r"\\.\physicaldrive0",s)=='':
break
else:
s=s*10
print(s)
else:
while True:
if read_sector("/dev/sda",s)=='':
break
else:
s=s*10
print(s)
def read_sector(disk, sector_no=0):
f = open(disk, 'rb')
f.seek(sector_no * 1)
read = f.read(1)
return read
if __name__ == "__main__":
main()
or
import os
def main():
s=0
if os.name == "nt":
while True:
if read_sector(r"\\.\physicaldrive0",s)=='':
break
else:
s=s+1
print(s)
else:
while True:
if read_sector("/dev/sda",s)=='':
break
else:
s=s+1
print(s)
def read_sector(disk, sector_no=0):
f = open(disk, 'rb')
f.seek(sector_no * 1)
read = f.read(1)
return read
if __name__ == "__main__":
main()

import os
def end_sector(disk):
os.system("fdisk -l %s >fdisk.lst"%disk)
with open("fdisk.lst") as file:
dosya=file.read()
dosya=dosya.split()
j=0
for i in dosya:
j=j+1
for i in range(j):
if dosya[i]=="sektör":
max_sector=int(dosya[i-1])
for i in range(j):
if dosya[i]=="=" and dosya[i-1]==dosya[i+1]:
sector_size=int(dosya[i+1])
return max_sector,sector_size
dizi=end_sector("/dev/sdb")
print(dizi)

Related

Escape Sequences in Python Not Working in CMD

import time
listy = ['timer','stopwatch']
def intro():
print("This is a program which contains useful tools")
print(listy)
def timer():
x = int(input("How long Seconds ?"))
while x > 0:
print(x)
time.sleep(1)
x -= 1
def stopwatch():
verif = input("Do you want to start y/n \n")
if verif == 'y':
x = 0
while True:
print(x, end = "\b"*5)
time.sleep(1)
x += 1
def main():
intro()
decider = input("Which Program?")
if decider.lower() == 'timer':
timer()
elif decider.lower() == 'stopwatch':
stopwatch()
main()
in this code i dont know why the \b escape sequence isnt working in cmd or in idle, can anyone explain why? Is it because of a logic error?
A flush may be required. How about...
print("{0}{1}".format("\b"*5, x), end="", flush=True)

Using random numbers to determine the length of a random number list

I'm trying to generate a list of random odd numbers in a specific range with the length of the list generated by calling another random number in PYTHON (and then writing them to a file).
I've been able to generate the initial random number (and threw in a display caller to see what it was). When I try to use it as the length of the list of the other of randomly generated numbers it doesn't work. I'm not certain why. Any insight would be appreciated. Here's what I've got...
import random
def main():
digit_file = open("numbers.txt","w")
file_size = random.randint(4,7)
print (file_size)
print ("is the file size\n" )
for n in range(file_size):
rand_output = random.randint(5,19)
if n %2 != 0:
print(rand_output)
digit_file.write(str(rand_output))
digit_file.close
print("File was created and closed.")
main()
Not sure to understand what you expect but what about using choice ?
from random import randint,choice
def main():
with open("numbers.txt","w") as digit_file:
file_size = randint(4,7)
print (file_size)
print ("is the file size\n" )
for n in range(file_size):
rand_output = choice(range(5, 19, 2))
print(rand_output)
digit_file.write(str(rand_output))
print("File was created and closed.")
main()
That can become :
from random import randint,choice
def main():
with open("numbers.txt","w") as f:
file_size = randint(4,7)
print ("%dis the file size\n" % file_size)
f.write(''.join(str(choice(range(5, 19, 2))) for _ in range(file_size)))
print("File was created and closed.")
main()
You have to check if rand_output % 2 != 0 not n % 2 != 0 :
import random
def main():
digit_file = open("numbers.txt", "w")
file_size = random.randint(4, 7)
print(file_size)
print("is the file size\n")
while file_size:
rand_output = random.randint(5, 19)
if rand_output % 2 != 0:
print(rand_output)
digit_file.write(str(rand_output))
file_size -= 1
digit_file.close()
print("File was created and closed.")
main()

Stuck in a While True loop... any ideas on how to get out?

Edit #1: Here is the working code, however I sometimes get a UnicodeDecodeError which halts the loop from continuing. Is there anyway to cause a break or pass in the loop when this occurs? I have tried changing the code to Try instead of If statements and its not working...
My issue is in the while True: statement...
def SerialRead(dataReadEvent):
delay1 = DT.datetime.now()
dataReadEvent.set()
#Serial Reading
ser = serial.Serial(port='COM4', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=None)
global last_received
buffer = ''
amountAppended = 0
while True:
buffer += ser.read(ser.inWaiting()).decode('ascii')
if '\n' in buffer:
last_received, buffer = buffer.split('\n')[-2:]
amountAppended += 1
if amountAppended == 2:
amountAppended =0
break
else:
ser.close()
global plaintext1
plaintext1 = last_received.replace(' ', ', ')
plaintext = plaintext1.replace('=', ', ')
global listvalue
listvalue = plaintext.split(", ")
#Writing to csv
outputfile = open(location, mode='a', newline='')
outputWriter = csv.writer(outputfile)
outputWriter.writerow([plaintext])
outputfile.close()
delay2 = DT.datetime.now()
differencetime = (delay2 - delay1).total_seconds()
restart = (writedelay - differencetime)
threading.Timer(restart, SerialRead, args=(dataReadEvent,)).start()
I have trying to get it so that my serial connection reads the last line of input every 5 seconds. However, I have seeded a While True loop inside a threading command and I cannot get out of the While True loop... its always once it is engaged.
The While True Loop allows me to get one complete line of serial data from my unit. I need a full proper line and this was the way to do it, but it snags every time. How can I get out of the Loop?
from PyQt4 import QtGui, QtCore
import sys
import masimo
import csv
import time
import datetime as DT
import threading
from threading import Thread
import serial
import os
os.chdir(r"C:\Users\SpO2\Desktop\Data")
time1 = time.strftime("%d %b %Y %H%M%S")
location = r'%s.csv' % time1
outputfile = open(location, mode='x', newline='')
outputWriter = csv.writer(outputfile)
outputWriter.writerow(["start"])
outputfile.close()
writedelay = int(5)
last_received = ''
class ExampleApp(QtGui.QMainWindow, masimo.Ui_MainWindow):
def __init__(self, event, parent=None):
super(self.__class__, self).__init__()
self.setupUi(self)
self.dataWasReadEvent = event
self.checkThreadTimer = QtCore.QTimer(self)
self.checkThreadTimer.setInterval(500) #.5 seconds
self.checkThreadTimer.timeout.connect(self.readListValues)
self.checkThreadTimer.start()
def readListValues(self):
if self.dataWasReadEvent.is_set():
#Read your events from the list and update your fields
self.SPO2text.setText(str(listvalue[5]))
self.HRtext.setText(str(listvalue[7]))
self.PItext.setText(str(listvalue[9]))
self.timestamptext.setText(str(listvalue[1]))
self.rawdata.setText(str(plaintext1))
self.dataWasReadEvent.clear() #Clear the event set flag so that nothing happens the next time the timer times out
def SerialRead(dataReadEvent):
delay1 = DT.datetime.now()
dataReadEvent.set()
#Serial Reading
ser = serial.Serial(port='COM4', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=2)
global last_received
buffer = ''
while True:
buffer += ser.read(ser.inWaiting()).decode('ascii')
if '\n' in buffer:
last_received, buffer = buffer.split('\n')[-2:]
else:
ser.close()
global plaintext1
plaintext1 = last_received.replace(' ', ', ')
plaintext = plaintext1.replace('=', ', ')
global listvalue
listvalue = plaintext.split(", ")
#Writing to csv
outputfile = open(location, mode='a', newline='')
outputWriter = csv.writer(outputfile)
outputWriter.writerow([plaintext])
outputfile.close()
delay2 = DT.datetime.now()
differencetime = (delay2 - delay1).total_seconds()
restart = (writedelay - differencetime)
threading.Timer(restart, SerialRead, args=(dataReadEvent,)).start()
def main(dataReadEvent):
app = QtGui.QApplication(sys.argv)
form = ExampleApp(dataReadEvent)
form.show()
sys.exit(app.exec_())
if __name__ == '__main__':
dataReadEvent = threading.Event()
Thread(target = SerialRead, args=(dataReadEvent,) ).start()
Thread(target = main, args=(dataReadEvent,) ).start()
The
while True:
function will never end and will never exit, you can use "break" to exit a loop. if this isn't what you want you will have to tell it when the while statement should be active ie:
While amountOfTimesToLoop < 0: do whatever
If you want to check for when things have been appended to your list you can do something like
while True:
buffer += ser.read(ser.inWaiting()).decode('ascii')
if '\n' in buffer:
last_received, buffer = buffer.split('\n')[-2:]
if last_received.length == 2:
break
else:
ser.close()
or if you aren't clearing the list you could something like
amountAppended = 0
while True:
buffer += ser.read(ser.inWaiting()).decode('ascii')
if '\n' in buffer:
last_received, buffer = buffer.split('\n')[-2:]
amountAppended += 1
if amountAppended == 2:
amountAppended = 0
break
else:
ser.close()
Use the break keyword to exit any loop. It will exit whatever loop the break is in.
Your loop begins with
while True:
This will always continue forever look at these two examples and note the differences
a=0
while a<10:
print a
a = a+1
This will print 0 1 2 3 4 ... 9 and then a is incremented to 10. the expression evaluates to false and the loop exits.
Now:
a=1
while a>0:
print a
a = a+1
This will run forever since a always greater than 0
In response to your comment:
Use the having two lines in last_recieved as the test then.
while last_received_count <2:
....
....
if '\n' in buffer:
last_received, buffer = buffer.split('\n')[-2:]
last_received_count = last_received_count+1
As you want to "run the loop until i have two lines of data appended to 'last_received'", you can use a counter which increments inside the if statement and then break when the counter value is equals to 2. Something like this:
counter = 1
while True:
buffer += ser.read(ser.inWaiting()).decode('ascii')
if '\n' in buffer:
last_received, buffer = buffer.split('\n')[-2:]
if counter == 2:
break
counter += 1

How to get rid of frame 'blinking' effect with standard libs?

I am currently playing with some cmd/prompt animations/graphics:
import os
import time
def printFrame(timeout, count):
os.system('cls')
l=0
while True:
for k in range(0,9):
for i in range(0,9):
for j in range(0,9):
if j == k and i != 4:
print("|", end="", flush=True)
elif j !=k and i == 4:
print("-", end="", flush=True)
elif j ==k and i == 4:
print("+", end="", flush=True)
else:
print("O", end="", flush=True)
print("")
time.sleep(timeout)
os.system('cls')
l += 1
if l > count:
break
if __name__ == "__main__":
printFrame(0.08, 2)
and i want to get rid of frame blinking - especialy visible in first line, my idea was to use second printing thread:
def printFrame(timeout, count):
#print from example1
def printFrameTwo(timeout, count):
#print from example1 without os.system('cls')
if __name__ == "__main__":
p1 = threading.Thread(target = printFrame, args = (0.08, 2))
p2 = threading.Thread(target = printFrameTwo, args = (0.08, 2))
p1.start()
p2.start()
but the effect was rather disappointing - problems with synchronization and first line still very blinky, second idea was to use 'predefined frames' - but its not very educating - the bonus here is that I can print whole line at once, but still effect is not as expected, third (most promising) idea is to only change necessary 'pixels'/chars in frame - but here I need to move in frame between lines! and curses is not working on windows (at least not in standard). Do you maybe have some ideas how to bite it? (windows, standard libraries) maybe how to speed up 'os.system('cls')'?
I figured it out... You can use ANSI codes to move the cursor then clear the lines without any BLINK!
print('\033[4A\033[2K', end='')
\033[4A Moves the cursor 4 lines up (\033[{lines}A you can replace lines with however many you need) \033[2K Clears all those lines without the screen blinking. You can use it in a simple typewrite function that needs a constant message or a box around it like this:
from time import sleep
def typewrite(text: str):
lines = text.split('\n')
for line in lines:
display = ''
for char in line:
display += char
print(f'╭─ SOME MESSAGE OR SOMEONES NAME ────────────────────────────────────────────╮')
print(f'│ {display:74} │') # :74 is the same as ' ' * 74
print(f'╰────────────────────────────────────────────────────────────────────────────╯')
sleep(0.05)
print('\033[3A\033[2K', end='')
The only problem with this is that the top line is blinking. To fix this all we need to do is to add a empty line that is blinking so the user cant see it. We also move the cursor up from 3 to 4 lines.
def typewrite(text: str):
lines = text.split('\n')
for line in lines:
display = ''
for char in line:
display += char
print('')
print(f'╭─ SOME MESSAGE OR SOMEONES NAME ────────────────────────────────────────────╮')
print(f'│ {display:74} │') # :74 is the same as ' ' * 74
print(f'╰────────────────────────────────────────────────────────────────────────────╯')
sleep(0.05)
print('\033[4A\033[2K', end='')
To make this into your code just print your text and add a print('') at the start. Then use this print('\033[4A\033[2K', end='') but change the 4 to however many lines that you printed including the print(''). Then it should work without blinking. You can put print('\033[4B', end='') at the end which just moves the cursor back up.
If you want to hide the cursor you can use this gibberish or make the cursor the same color as the background:
import ctypes
if os.name == 'nt':
class _CursorInfo(ctypes.Structure):
_fields_ = [("size", ctypes.c_int),
("visible", ctypes.c_byte)]
def hide_cursor() -> None:
if os.name == 'nt':
ci = _CursorInfo()
handle = ctypes.windll.kernel32.GetStdHandle(-11)
ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
ci.visible = False
ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
def show_cursor() -> None:
if os.name == 'nt':
ci = _CursorInfo()
handle = ctypes.windll.kernel32.GetStdHandle(-11)
ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
ci.visible = True
ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
Note: All of this is still new to me so I am still testing this out to fully understand it.

(python) append used to list, then only return value if it hasn't been used

The title pretty much says it all. Following is the barebones of a small Japanese learning game that I wrote. I need to only print the kana if it has not already been printed in the current loop. Can anyone see what it is that I'm doing wrong? Thank you :)
#!/usr/bin/python
from os import system as cmd
from random import choice as random
from time import sleep
from sys import platform
m = ["ma", "mi", "mu", "me", "mo"]
y = ["ya", "yu", "yo"]
n = ["n"]
def get_dict(group):
if group == 1:
return m
elif group == 13:
return y
elif group == 14:
return n
elif group == 15:
return m + y + n
def clear():
if "win" in platform: cmd("cls")
if "lin" in platform: cmd("clear")
def get_kana():
global kana
return random(kana)
## Initiate ##
kana = get_dict(15)
speed = speed()
clear()
print disp
print "Please get ready!..."
sleep(5)
def chk_used():
global used_kana
numlpo = 0
while numlpo < 50:
numlpo = numlpo + 1
kana = get_kana()
if kana not in used_kana:
used_kana = used_kana.append(kana)
return kana
break
def main():
used_kana = []
while True:
clear()
print disp
print "Please write the following kana: \n"
print " " + chk_used()
sleep(3)
main()
A couple things:
In chk_used, you have the line:
used_kana = used_kana.append(kana)
There's only one problem. list.append() returns None. Every time you do this, you're appending kana to used_kana, but then you're setting the value of used_kana to None.
used_kana.append(kana)
will suffice
You define used_kana within a function
def main():
used_kana = []
But you try to refer to it globally. Python looks for a global variable and won't find one.
def chk_used():
global used_kana
The solution:
pass used kana as an argument to chk_used()
def chk_used(usedCharacters):
...
def main():
used_kana = []
...
print " " + chk_used(used_kana)
Finally:
if kana not in used_kana:
used_kana.append(kana)
return kana
break #there's no reason for this break. the return on the line before exits the function, your code will never ever execute this line.

Categories