Python Jupyter Notebook loops while writing output to a text file - python-3.x

A jupyter notebook cell is calculating some things and prints the results.
I would like to print everything into a text file. The text file is created and written. But maybe the cell isnt properly closed as it never comes to an running end? Where is my mistake?
The code:
with open(path_out + day_number + 'factsheet.txt', 'w') as fs:
sys.stdout = fs
print("Fact Sheet:")
Lat_start = df.Wgs84Latitude[df.index.min()]
Lon_start = df.Wgs84Longitude[df.index.min()]
print("Coordinates: " , Lat_start,'°N , ', Lon_start,'°E')
print("Min. Humidity: " + "{:12.2f}".format(df.humidity.min()) + " %")
print("Max. Humidity: " + "{:12.2f}".format(df.humidity.max()) + " %")
print("Min. Temperature: " + "{:9.2f}".format(df.temperature.min()) + " °C")
print("Max. Temperature: " + "{:9.2f}".format(df.temperature.max()) + " °C")
sys.stdout = original_stdout # Reset the standard output to its original value
fs.close()
Any hint for me?

I found a solution that works without tapping into a loop, but I still do not understand why the above code leads to loop the cell.
My "workaround":
fs = open(path_out + day_number + '_factsheet.txt', 'w')
Lat_start = df.Wgs84Latitude[df.index.min()]
Lon_start = df.Wgs84Longitude[df.index.min()]
fs.write("Coordinates: " + str(Lat_start) + '°N , ' + str(Lon_start) + '°E\n\n')
fs.write("Min. Humidity: " + "{:12.2f}".format(df.humidity.min()) + " %\n")
fs.write("Max. Humidity: " + "{:12.2f}".format(df.humidity.max()) + " %\n")
fs.write("Min. Temperature: " + "{:9.2f}".format(df.Temperature.min()) + " °C\n")
fs.write("Max. Temperature: " + "{:9.2f}".format(df.Temperature.max()) + " °C\n")
fs.close()
print("Export successful")
Remark: This solution accepts only the "+"-symbol to add several contents in one write-break and I had to add th "\n" to insert a line feed which was not neccessary in the "print" solution.
But it works :-)

Related

ending my total with two zeros, i cant find anything on the internet that is clear to me

#Let's start a coffee shop together!! We're going to build a coffee shop using some new Python programming concepts!!
#Let's build robot Barista!!
from time import sleep
print("\nHello! Welcome to Star Bucks.")
name = input("What is your name?\n")
print("Hello " + name + ", thank you so much for coming in today.\n")
sleep(2)
#To make it wait two seconds before showing the menu
menu = "Black Coffee, Espresso, Latte, Cappucino"
print (name + ", what would you like from our menu today? Here is what we are serving.\n" + menu)
order = input()
price = float(2.50)
quantity = input("How many " + order + "'s would you like?\n")
total = price * float(quantity)
print(format("Thank you. Your total of " + quantity + " " + order + " will be €" + str(total)))
print("\nSounds good " + name + ", we'll have your " + quantity + " " + order + "'s ready for you in a moment.")
You need to format the float like this "{:.2f}".format(total)
Your last line becomes:
print(format("Thank you. Your total of " + quantity + " " + order + " will be €" + "{:.2f}".format(total)))

Telnet.read_very_eager in FOR loop and the first often returns b' ' while the rest works fine

I'm using Telnetlib to control a VIAVI 5800.Here is my code.
And I log results of telnet.read_very_eager. Sometimes the first read returns b'', maybe say it occurs a lot. I really don't understand why only the first read has this problem while the others just work fine. I also tried adding more time after I finishing changing the time slot, this still happens.
import telnetlib
import time
from robot.libraries.BuiltIn import BuiltIn
for vc4 in range(vc4, vc4_end):
for tug3 in range(stm_start, tug3_end):
for tug2 in range(1, 8):
for tu12 in range(1, 4):
tu12_com = ":SENSE:SDH:DS1:E1:LP:C12:CHANNEL" + " " + str(tu12) + "\n"
tug2_com = ":SENSE:SDH:DS1:E1:LP:C2:CHANNEL" + " " + str(tug2) + "\n"
tug3_com = ":SENSE:SDH:DS1:E1:LP:C3:CHANNEL" + " " + str(tug3) + "\n"
vc4_com = ":SENSE:SDH:CHANNEL:STMN" + " " + str(vc4)
tn.write(tu12_com.encode('ascii')) # change tu12
time.sleep(0.1)
tn.write(tug2_com.encode('ascii')) # change tug2
time.sleep(0.1)
tn.write(tug3_com.encode('ascii')) # change tug3
time.sleep(0.1)
tn.write(vc4_com.encode('ascii')) # change vc4
time.sleep(1.5)
tn.write(b":ABOR\n")
time.sleep(1)
tn.write(b":INIT\n")
time.sleep(5)
tn.write(b":SENSE:DATA? TEST:SUMMARY\n")
time.sleep(2)
result = tn.read_very_eager()
result_num = str(vc4) + "-" + str(tug3) + "-" + str(tug2) + "-" + str(tu12)
BuiltIn().log_to_console(result_num)
BuiltIn().log_to_console(result)
The results are like under:
results saved in excel workbook
results in RF Ride console
I'm so confused and wondering can anyone explain this. Thanks a lot.
BTW, my python version is:
C:\Users\Quinn>python -V
Python 3.7.9

how do i loop on computed field to make it's computed method change if one field related False?

i make a computed field char that get values as strings from fields but empty field get False as string , i need when any field equal False ignore it from computing ?
i tried to make a model_field as example if false do another compute method
#api.one
#api.depends('car','model','dsc','drc','year','org')
def _compute_amount(self):
for self in self:
if self.model.name:
self.model= False
self.name = str(str(self.car.name) + " " + str(self.dsc.name) + " " + str(self.drc.name) + " " + str(self.year.name)+" " +str(self.org.name))
else:
model=self.model
name = str(str(self.car.name) + " " + str(self.model.name) + " " + str(self.dsc.name) + " " + str(self.drc.name) + " " +str(self.org.name)+ " " +str(self.year.name))
the value of my code that all field be false when model_field is false
Your code is not even remotely close to what you should do to get your value, try learning Python basic for example looping and conditioning before you jump to code in a framework. Meanwhile, check following code, should serve your purpose
#api.multi
#api.depends('car','model','dsc','drc','year','org')
def _compute_amount(self):
name_fields = ('car','model','dsc','drc','year','org')
for record in self:
computed_name = ""
for field in name_fields:
field_value = getattr(record, field)
if field_value:
computed_name += field_value.name
record.name = computed_name

specific arguments for geocoder in google

import geocoder
g = geocoder.google([self.getLatitude(), self.getLongitude()], method = 'reverse')
return g.street + " " + g.housenumber + ", " + g.postal + " " + g.city + ", " + g.country
So I have this code and my problem is, that I can't find any arguments that specify my choosen language and the length of the country in the output. Eg. I have 'CH' and I'd like to have 'Switzerland'.
I don't think you will get GeoCoder to do that. But you can translate the code yourself.
$ pip install iso3166
>>> from iso3166 import countries
>>> countries.get("CH")
Country(name='Switzerland', alpha2='CH', alpha3='CHE', numeric='756', apolitical_name='Switzerland')

PKCS11 Python FindObjects in available slots

I wrote a script in python that gets info from a Cryptoki library. From there I can make (only)LowLevel API calls such as:
C_getInfo
C_GetSlotList
C_SlotInfo
C_OpenSession
C_GetTokenInfo
C_Logout
C_CloseSession
C_Initialize
Here's a few examples on their implementation
a.C_Initialize()
print("C_GetInfo:", hex(a.C_GetInfo(info)))
print("Library manufacturerID:", info.GetManufacturerID())
del info
print("C_GetSlotList(NULL): " + hex(a.C_GetSlotList(0, slotList)))
print("\tAvailable Slots: " + str(len(slotList)))
for x in range(len(slotList)):
print("\tC_SlotInfo(): " + hex(a.C_GetSlotInfo(slotList[x], slotInfo)))
print("\t\tSlot N." + str(x) + ": ID=" + str(slotList[x]) + ", name='" + slotInfo.GetSlotDescription() + "'")
print("\tC_OpenSession(): " + hex(a.C_OpenSession(slotList[x], CKF_SERIAL_SESSION | CKF_RW_SESSION, session)))
print("\t\tSession:" + str(session))
#print("\tMechList:" + hex(a.C_GetMechanismList(0, slotList[x])))
print("\tC_GetTokenInfo(): " + hex(a.C_GetTokenInfo(slotList[x], tokenInfo)))
print("\t\tTokenInfo: Label=" + tokenInfo.GetLabel() + ", ManufacturerID=" + tokenInfo.GetManufacturerID())
print("\t\tTokenInfo: flags=" + hex(tokenInfo.flags) + ", Model=" + tokenInfo.GetModel())
print("\tC_Login(): " + hex(a.C_Login(session, CKU_USER, pin)))
print("\t\tSessionInfo: state=" + hex(sessionInfo.state) + ", flags=" + hex(sessionInfo.flags))
QUESTION
I can't seem to figure out what api call is needed to find objects in the slot list.. i have something like print("Finding objects: " + hex(a.C_FindObjects(slotList[x], CKA_CLASS, CKO_CERTIFICATE)))
I'm not sure what arguments to pass or if it's structured the right way.
Im using this documentation LowLevel API pkcs11
Ultimately I'm trying to extract the specific omnikey smart card token.. use its private key and cert to sign and verify data..
SearchResult = PyKCS11.LowLevel.ckobjlist(10)
SearchTemplate = PyKCS11.LowLevel.ckattrlist(0)
print "C_FindObjectsInit: " + hex(a.C_FindObjectsInit(session,SearchTemplate))
print "C_FindObjects: " + hex(a.C_FindObjects(session, SearchResult))
print "C_FindObjectsFinal: " + hex(a.C_FindObjectsFinal(session))
First you have to make a result variable and use it to search the object list. I passed 10 in, as I knew there were only a handful of objects and tokens within the list. You can construct a template variable that searches each object for specific attributes, such if it is Private, Modifiable, Key Type, Encrypt, etc. Then you have to make (a.C_FindObjectsInit(session,SearchTemplate)) call to initialize the search in the session by template specifications. Working with the LowLevel API can be confusing, there is virtually no documentation. Hope this helps.

Resources