I work actually on my raspberry 3 without internet for my internship.
Firstly I created a python script that I schedule with Cron to update my raspberry's hour every 12h.
Secondly, I have another script should run continually.
But I observed that, when I update the time, my script that run continually, doesn't update its datetime.
So I would like to reboot it, to allow the script to take the time in consideration.
here my script I would like to reboot.
from math import *
import pyorbital
from pyorbital import tlefile
from pyorbital.orbital import Orbital
import serial
import time
from datetime import datetime
import os
import sat_class
import predict
import rotator_treshold_test
def rotator_set (azel,v):
if v == False:
az = 0
el = 90
print(('waiting \n azimuth = %f elevation = %f\n\n')%(az,el))
else:
az = azel[0]
if azel[1] < 0:
el = 0
else :
el = azel[1]
print(('tracking satellite \n azimuth = %f elevation = %f\n\n')%(az,el))
def satellite_track():
k=0
saved = [0]
p = '?'
b = '?'
sat = sat_class.Satellite()
mission = predict.Mission()
verif = mission.verif
if verif == False:
mission = predict.Mission()
now= mission.now
print(now)
azel = [0,0] # we don't need to put azel here we are in waiting mode .
rotator_set(azel,verif)
time.sleep(29)
else :
mission= predict.Mission()
print("current time1: ",mission.now,'\n',mission.start,' ',mission.end)
verif1 = mission.verif
end = mission.end
now2 = mission.now
while now2 <= end :
azel = rotator_treshold_test.az_correct(saved[k])
rotator_set(azel,verif1)
saved.append(rotator_treshold_test.az_correct(azel[0]))
k+=1
mission = predict.Mission()
now2 = mission.now
print(now2)
time.sleep(0.8)
##I would like to reboot my script here
while True :
satellite_track()
You could use os.execl() to restart the program.
Source: https://docs.python.org/3/library/os.html#os.execl
Related
I am trying to use pystray to create a icon on tasktray, it is working on windows but now I am building one for Mac. I need the program minimize to tasktray on run on background. so I need to use icon.run_detached() instead of icon.run().
However, it keep crashing the app and I read the documents seems that I need to give some darwin_nsapplication = AppKit.NSApplication.sharedApplication() to the code but I really don't know how to implement this. here is my code.
import tkinter as tk
import time
import pystray
from tkinter import *
from tkinter import messagebox
from PIL import Image
import AppKit
`class Gui():
def __init__(self):
self.window = tk.Tk()
self.darwin_nsapplication = AppKit.NSApplication.sharedApplication()
self.image = Image.open("./images/noname.png")
self.menu = (
pystray.MenuItem('Show', self.show_window),
pystray.MenuItem('Quit', self.quit_window)
)
# Declaration of variables
self.hour=StringVar()
self.minute=StringVar()
self.second=StringVar()
# setting the default value as 0
self.hour.set("00")
self.minute.set("00")
self.second.set("00")
# Use of Entry class to take input from the user
hourEntry= Entry(self.window, width=3, font=("Arial",18,""),
textvariable=self.hour)
hourEntry.place(x=80,y=20)
minuteEntry= Entry(self.window, width=3, font=("Arial",18,""),
textvariable=self.minute)
minuteEntry.place(x=130,y=20)
secondEntry= Entry(self.window, width=3, font=("Arial",18,""),
textvariable=self.second)
secondEntry.place(x=180,y=20)
# button widget
btn = Button(self.window, text='Set Time Countdown', bd='5',
command= self.submit)
btn.place(x = 70,y = 120)
def submit(self):
try:
# the input provided by the user is
# stored in here :temp
temp = int(self.hour.get())*3600 + int(self.minute.get())*60 + int(self.second.get())
except:
print("Please input the right value")
while temp >-1:
# divmod(firstvalue = temp//60, secondvalue = temp%60)
mins,secs = divmod(temp,60)
# Converting the input entered in mins or secs to hours,
# mins ,secs(input = 110 min --> 120*60 = 6600 => 1hr :
# 50min: 0sec)
hours=0
if mins >60:
# divmod(firstvalue = temp//60, secondvalue
# = temp%60)
hours, mins = divmod(mins, 60)
# using format () method to store the value up to
# two decimal places
self.hour.set("{0:2d}".format(hours))
self.minute.set("{0:2d}".format(mins))
self.second.set("{0:2d}".format(secs))
# updating the GUI window after decrementing the
# temp value every time
self.window.update()
time.sleep(1)
# when temp value = 0; then a messagebox pop's up
# with a message:"Time's up"
if (temp == 0):
messagebox.showinfo("Time Countdown", "Time's up ")
# after every one sec the value of temp will be decremented
# by one
temp -= 1
def quit_window(self):
self.icon.stop()
self.window.destroy()
def show_window(self):
self.icon.stop()
self.window.protocol('WM_DELETE_WINDOW', self.withdraw_window)
self.window.after(0, self.window.deiconify)
def withdraw_window(self):
self.window.withdraw()
self.icon = pystray.Icon("name", self.image, "title", self.menu)
self.icon.run_detached()
if __name__ in '__main__':
app = Gui()
app.window.protocol('WM_DELETE_WINDOW', app.withdraw_window)
app.window.mainloop()`
I tried to add darwin_nsapplication to icon like self.icon = pystray.Icon("name", self.image, "title", self.menu,self.darwin_nsapplication)
But it is said 6 arguments are given, 2-5 are needed.
How to get all installed font path with pywin32?
I can only find a way with registry key, but I would prefer to directly use GDI or DirectWrite.
Edit:
I am not sure, but from what I can see, here is how it would maybe be possible with GDI:
Create Factory: https://learn.microsoft.com/en-us/windows/win32/api/dwrite/nf-dwrite-dwritecreatefactory
GetSystemFontCollection: https://learn.microsoft.com/en-us/windows/win32/api/dwrite/nf-dwrite-idwritefactory-getsystemfontcollection
Do a for loop with GetFontFamilyCount: https://learn.microsoft.com/en-us/windows/win32/api/dwrite/nf-dwrite-idwritefontcollection-getfontfamilycount
GetFontFamily: https://learn.microsoft.com/en-us/windows/win32/api/dwrite/nf-dwrite-idwritefontcollection-getfontfamily
GetMatchingFonts (the param weight, stretch, style can be anything. These param seems to only change the order or the return list): https://learn.microsoft.com/en-us/windows/win32/api/dwrite/nf-dwrite-idwritefontfamily-getmatchingfonts
Do a for loop with GetFontCount:https://learn.microsoft.com/en-us/windows/win32/api/dwrite/nf-dwrite-idwritefontlist-getfontcount
GetFont: https://learn.microsoft.com/en-us/windows/win32/api/dwrite/nf-dwrite-idwritefontlist-getfont
CreateFontFace: https://learn.microsoft.com/en-us/windows/win32/api/dwrite/nf-dwrite-idwritefont-createfontface
GetFiles: https://learn.microsoft.com/en-us/windows/win32/api/dwrite/nf-dwrite-idwritefontface-getfiles
GetReferenceKey: https://learn.microsoft.com/en-us/windows/win32/api/dwrite/nf-dwrite-idwritefontfile-getreferencekey
Again DWriteCreateFactory but with uuidof IDWriteLocalFontFileLoader
GetFilePathFromKey: https://learn.microsoft.com/en-us/windows/win32/directwrite/idwritelocalfontfileloader-getfilepathfromkey
I found an solution.
I used DirectWrite API.
This code depends on pyglet librairy.
import sys
import time
from ctypes import byref, c_uint32, create_unicode_buffer
from pyglet.font.directwrite import (
DWriteCreateFactory,
DWRITE_FACTORY_TYPE_ISOLATED,
IDWriteFactory,
IDWriteFont,
IDWriteFontCollection,
IDWriteFontFace,
IDWriteFontFamily,
IDWriteFontFile,
IDWriteFontFileLoader,
IDWriteLocalFontFileLoader,
IID_IDWriteFactory,
IID_IDWriteLocalFontFileLoader,
)
from pyglet.libs.win32.types import c_void_p
from typing import List
def get_fonts_filepath() -> List[str]:
"""
Return an list of all the font installed.
"""
write_factory = IDWriteFactory()
DWriteCreateFactory(
DWRITE_FACTORY_TYPE_ISOLATED, IID_IDWriteFactory, byref(write_factory)
)
fonts_path = set()
sys_collection = IDWriteFontCollection()
write_factory.GetSystemFontCollection(byref(sys_collection), 0)
collection_count = sys_collection.GetFontFamilyCount()
for i in range(collection_count):
family = IDWriteFontFamily()
sys_collection.GetFontFamily(i, byref(family))
font_count = family.GetFontCount()
for j in range(font_count):
font = IDWriteFont()
family.GetFont(j, byref(font))
font_face = IDWriteFontFace()
font.CreateFontFace(byref(font_face))
file_ct = c_uint32()
font_face.GetFiles(byref(file_ct), None)
font_files = (IDWriteFontFile * file_ct.value)()
font_face.GetFiles(byref(file_ct), font_files)
pff = font_files[0]
key_data = c_void_p()
ff_key_size = c_uint32()
pff.GetReferenceKey(byref(key_data), byref(ff_key_size))
loader = IDWriteFontFileLoader()
pff.GetLoader(byref(loader))
try:
local_loader = IDWriteLocalFontFileLoader()
loader.QueryInterface(
IID_IDWriteLocalFontFileLoader, byref(local_loader)
)
except OSError: # E_NOTIMPL
font.Release()
font_face.Release()
loader.Release()
pff.Release()
continue
path_len = c_uint32()
local_loader.GetFilePathLengthFromKey(
key_data, ff_key_size, byref(path_len)
)
buffer = create_unicode_buffer(path_len.value + 1)
local_loader.GetFilePathFromKey(key_data, ff_key_size, buffer, len(buffer))
font.Release()
font_face.Release()
loader.Release()
local_loader.Release()
pff.Release()
fonts_path.add(buffer.value)
family.Release()
sys_collection.Release()
write_factory.Release()
return list(fonts_path)
def main():
start = time.time()
fonts_path_dwrite = get_fonts_filepath()
print(time.time() - start)
print(fonts_path_dwrite)
if __name__ == "__main__":
sys.exit(main())
When running the Function with no names on the input lists, it gives everyone the approtriate time based on the varible listed. If we have the input varibale have a name it gives everyone time off instead of just that indivudual.
There are some lists associated with this as well and that part works fine.
this is the required resources:
from openpyxl import Workbook
from datetime import timedelta, datetime
import random
def add_agents_w1():
num = 4
c = ["B","C","D","E","F"]
tow1 = input("IF anyone taking time off enter 1st
person now: \n")
tow12 = input("If someone else is taking time off enter
2nd person now: \n")
for x in tl:
ws1[f"A{num}"] = x
ws1[f"I{num}"] = x
for f in c:
if x in tow1 or tow12:
ws1[f'{f}{num}'] = "OFF"
else:
ws1[f"{f}{num}"] = s2t
num += 1
wb.save(dest_filename)
I'd like to implement a real time plot of my CPU and GPU load.
I already have a script that retrieve the data and echo it in a terminal.
What I want to do now is to plot this information to see the evolution with time.
I don't know if I need python for instance, and in this case using which module?
Is there any other alternative?
Does someone have any experience doing real time plotting?
Éric.
here is what I did so far
#! /usr/bin/python
import pylab
import time
t = 0
dt = .25
old = None
if __name__ == "__main__":
pylab.ion()
#pylab.xlabel('this is x!')
#pylab.ylabel('this is y!')
#pylab.title('My First Plot')
while True:
with open('/proc/stat') as stat:
new = map(float, stat.readline().strip().split()[1:])
if old is not None:
diff = [n - o for n, o in zip(new, old)]
idle = diff[3] / sum(diff)
pylab.clf()
pylab.plot(t,int(255 * (1 - idle)),'-b', label='cpu')
#print t,int(255 * (1 - idle))
pylab.draw()
old = new
time.sleep(dt)
t = t + dt
Well, something happens when I execute it but nothing is displayed.
Any suggestion?
Thank you,
Éric.
I'm trying to display a QLabel (without parent) at a fixed position using PyQt. The QLabel functions as a graphic that appears only for a moment, it's appears in the middle of the screen by default but I can't find how to move its position.
Any suggestion??
updated:
This is my code, maybe is a problem in the way I'm doing this:
from PyQt4.QtCore import Qt,QTimer
from PyQt4.QtGui import QLabel,QPixmap,QApplication
import os
import subprocess
class BrightnessControl(QLabel):
def __init__(self,parent=None):
self.__command__ = "nvclock -S%s"
self.__imgPath__ = "../../../../ui/alfredozn_vaio/brightness/img/"
self.__image__ = QPixmap()
super(BrightnessControl,self).__init__(parent,Qt.SplashScreen)
#self.loadImg(100)
def comman(self):
return self.__command__
def image(self):
return self.__image__
def imgPath(self):
return self.__imgPath__
def currentValue(self):
'''
Obtenemos el valor actual del smartdimmer
'''
res=subprocess.Popen(["smartdimmer","-g"],stdout=subprocess.PIPE)
return int(res.stdout.readline().split()[-1])
def loadImg(self,value):
'''
Aquí asumimos que el único medio de control será la aplicación, por lo que los valores se moverán en múltiplos de 10
'''
os.system(self.comman() % str(value))
self.image().load("%s%i.png" % (self.imgPath(),value))
self.setPixmap(self.image())
self.setMask(self.image().mask())
self.update()
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
try:
if len(sys.argv) < 2 :
raise ValueError
else:
val=10
if sys.argv[1] == "down":
val*=-1
elif sys.argv[1] != "up":
raise ValueError
form = BrightnessControl()
val += form.currentValue()
val = 20 if val < 20 else 100 if val > 100 else val
form.loadImg(val)
#This move function is not working
form.move(100,100)
form.show()
QTimer.singleShot(3000,app.quit)
app.exec_()
except ValueError:
print "Modo de uso: SonyBrightnessControl [up|down]"
You can use pos property or you can move it calling move() into the label. But it doesn't always work well. The best method from my experience is to use label.setGeometry() function.
If you want it in the middle of the screen the code should be like this (Is c++ code, I dont know python sorry):
label.setGeometry((this->width() - label.sizeHint().width()) / 2), (this->height() - label.sizeHint().height()) / 2, label.sizeHint().width(), label.sizeHint().height());
If you do this into the resizeEvent of the parent you will have it always in the center of it.
You can also optimize the code saving the sizeHint into a variable to not call it several times.
Use its pos property.