I want to write a program that can:
Open an application. (I successfully executed the application using the subprocess module)
Use the application. (How do I automate a task on that particular software? Is it possible? For example, the software would require me login and python and automatically login with my credentials and proceed to automate my typical usage like opening projects)
Close the application.
from datetime import datetime
import time
import os
import subprocess
os.chdir("../../Desktop/Sublime/Sublime Text 2") #Directory need to adjust to find teamviewer
print "Starting python..."
switch = True
activator1 = True
activator2 = True
startBoolean = True
exitBoolean = True
container = None
def startTimer(startTime , exitTime):
global dateTime
global startBoolean
global exitBoolean
dateTime = datetime.now().strftime('%H%M%S')
print "Current Time: " +dateTime+ "| Start Time: " +startTime +"| Exit Time: "+exitTime
if dateTime >= startTime:
startBoolean = False
print "start boolean: "+ str(startBoolean)
if dateTime >= exitTime:
exitBoolean = False
print "exit boolean: "+ str(exitBoolean)
return [startBoolean,exitBoolean]
def startApplication(startTime):
if dateTime >= startTime:
print "Launching Application..."
process = subprocess.Popen(["./sublime_text"],shell=True) #This is using ubuntu terminal command. Might need to change the command to fits other OS.
def stopApplication(exitTime):
if dateTime >= exitTime:
print "Exiting Application..."
process = subprocess.Popen(["killall sublime_text"],shell=True)
startTime = raw_input("Project Launch Time: ")
exitTime = raw_input("Project Exit time: ")
while switch:
startTimer(startTime , exitTime)
global container
container = startTimer(startTime , exitTime)
if container!=None:
if activator1==True:
if container[0] == False:
print "clear1"
activator1 = False #Cannot activate < 1.
startApplication(startTime)
if activator2==True:
if container[1] == False:
print "clear2"
activator2 = False #Cannot activate < 1.
stopApplication(exitTime)
Hi you can use pyAutoIt
I am giving sample code for Notepad to save it in required location and required path.
import autoit,time
autoit.run("notepad.exe")
autoit.win_wait_active("Untitled - Notepad")
time.sleep(5)
autoit.control_send("Untitled - Notepad", "Edit1", "hello world{!}")
autoit.control_send("Untitled - Notepad", "Edit1", "test-2")
#time.sleep(5)
autoit.win_close("Untitled - Notepad")
autoit.control_click("Notepad", "Button1")
#time.sleep(5)
autoit.win_wait_active("Save As")
#time.sleep(5)
autoit.control_send("Save As", "Edit1","Path-to-save")
autoit.control_send("Save As", "Edit1", "file-name")
autoit.control_click("Save As", "Button1")
pywinauto is also great GUI automation solution on Python.
Example:
from pywinauto import Application
app = Application().start(r"C:\Program Files\Sublime Text 2\sublime_text.exe")
app.untitled_SublimeText2.Wait('ready', timeout=10) # just for possible slow start
app.untitled_SublimeText2.MenuSelect('File->Open file')
app.Open.FilenameEdit.SetText('path to the project')
app.Open.Open.Click()
app.Open.WaitNot('visible') # just to make sure it's closed
main_window = app["project_name - Sublime Text 2"]
# print access names for all available controls on the main window
main_window.PrintControlIdentifiers()
There is also GUI helper SWAPY, pywinauto object inspector and code generator.
Related
I want to make a task/time manager. I want the list of tasks to be at the top and a question to add a new task if the user wants, but the problem is that I can't keep my to-do list in the top and I can't make it updated. What should I do?
This is my code, this is the form I want and the code I've written:
TASKS:(I want this to be updated)
1)--------
2)----------
3)----------
|
v
do you want to add a task(YES/NO):
when do you want to start the task (HOUR:MINUTE):
task_num = 0
k = False
print("YOUR TASKS")
if k == True:
print("\r", tasks)
print("tasks" + ":" + str(task_num), "\n\n")
active = True
while active:
add_task = input("do you want to add a task(YES/NO):",)
if add_task != 'YES':
active = False
else:
k = True
start_time = input("when do you want to start the task (HOUR:MINUTE):")
end_time = input("when do you want to complete it:")
task_name = input("what do you want to call it:")
start_h, start_m = start_time.split(":")
end_h, end_m = end_time.split(":")
duration = str(abs(int(end_h) - int(start_h))) + ":" + str(abs(int(end_m) - int(start_m)))
task = {"task name": task_name, "start time": start_time, "end time": end_time, "duration": duration}
task_num += 1
tasks[task_num] = task
for key in tasks.keys():
task_key = tasks[key]
print(key,end=")")
for key1 in task_key.keys():
print(key1, ":", task_key[key1], end='|',)
print('\n')
On POSIX systems clear -x command works like a charm. It preserves the current scroll buffer and produces almost zero flickering. Combine that with hiding the cursor, ah it is marvelous.
import sys
import subprocess
try:
sys.stdout.write('\033[?25l') # hide cursor
subprocess.run(['clear', '-x'])
finally:
sys.stdout.write('\033[?25h') # show cursor
sys.stdout.flush()
On Windows, on the other hand, you'll probably need colorama package installed and initialized.See https://github.com/tartley/colorama
On Windows cmd:
import sys
import shutil
height = shutil.get_terminal_size().lines
h = height * '\n'
# move cursor down and up.
sys.stdout.write(f'{h}\033[{height}A')
sys.stdout.flush()
On Windows Terminal and other modern terminal emulators:
import sys
import shutil
height = shutil.get_terminal_size().lines
# clear the screen with the ANSI sequence.
sys.stdout.write((height - 1) * '\n' + '\033[2J')
sys.stdout.flush()
Play with them and see what works for you.
i'm pretty new to python, so my knowledge is quiet basic. (i'm a system engineer)
i have a raspberry pi, an led strip and a python script to simulate a fire on the led strip :D
now i want to start the script by pressing my flic button. i found the fliclib sdk on github and installed it. my problem is now, how to handle the event correctly. i successfully can start the script, but i'd like to stop it by doublepress the flic button. but it seems like i'm stuck in the fire.py script as soon as i press the button once. can anybody help me how to set this up correctly please? :-)
Edit after suggestion:
i just edited my scripts as the following. i can see when the button is pressed once or twice with this output:
Starting Fire
Stopping Fire
but the led wont turn on, seems like, fire.py isn't opened or something like that.. when i set button=1 in fire.py itself, the fire turns on.
main.py
#!/usr/bin/env /usr/bin/python3
# -*- coding: utf-8 -*-
import flicbutton
import fire
button = 0
flicbutton.py
#!/usr/bin/env /usr/bin/python3
# -*- coding: utf-8 -*-
import fliclib
client = fliclib.FlicClient("localhost")
MyButton1 = '80:e4:da:71:83:42' #turquoise flic button
def got_button(bd_addr):
cc = fliclib.ButtonConnectionChannel(bd_addr)
cc.on_button_single_or_double_click_or_hold = some_handler
cc.on_connection_status_changed = \
lambda channel, connection_status, disconnect_reason: \
print(channel.bd_addr + " " + str(connection_status) + (" " + str(disconnect_reason) if connection_status == fliclib.ConnectionStatus.Disconnected else ""))
client.add_connection_channel(cc)
def got_info(items):
print(items)
for bd_addr in items["bd_addr_of_verified_buttons"]:
got_button(bd_addr)
def some_handler(channel, click_type, was_queued, time_diff):
if channel.bd_addr == MyButton1:
try:
if click_type == fliclib.ClickType.ButtonSingleClick:
print("Starting Fire")
button=1
if click_type == fliclib.ClickType.ButtonDoubleClick:
print("Stopping Fire")
button=2
if click_type == fliclib.ClickType.ButtonHold:
print("ButtonHold has not been assigned an action")
except Exception:
import datetime
print('An error occured: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
client.get_info(got_info)
client.on_new_verified_button = got_button
client.handle_events()
fire.py
import RPi.GPIO as GPIO
import threading
import time
import random
import math
R = 17
G = 22
pwms = []
intensity = 1.0
def initialize_gpio():
GPIO.setmode(GPIO.BCM)
GPIO.setup([17,22], GPIO.OUT)
def red_light():
p = GPIO.PWM(R, 300)
p.start(100)
pwms.append(p)
while True:
p.ChangeDutyCycle(min(random.randint(50, 100) * math.pow(intensity + 0.1, 0.75), 100) if intensity > 0 else 0)
rand_flicker_sleep()
def green_light():
global green_dc
p = GPIO.PWM(G, 300)
p.start(0)
pwms.append(p)
while True:
p.ChangeDutyCycle(random.randint(5, 10) * math.pow(intensity, 2) if intensity > 0 else 0)
rand_flicker_sleep()
def rand_flicker_sleep():
time.sleep(random.randint(3,10) / 100.0)
def fan_the_flame(_):
global intensity
intensity = min(intensity + 0.25, 1.0)
def light_candle():
threads = [
threading.Thread(target=red_light),
threading.Thread(target=green_light),
## threading.Thread(target=burning_down)
]
for t in threads:
t.daemon = True
t.start()
for t in threads:
t.join()
def startfire():
try:
initialize_gpio()
print("\nPress ^C (control-C) to exit the program.\n")
light_candle()
except KeyboardInterrupt:
pass
finally:
for p in pwms:
p.stop()
def stopfire():
GPIO.cleanup()
#if __name__ == '__main__':
# main()
if button == 1:
startfire()
if button == 2:
stopfire()
Have a common (global variable) that both codes can read, you can put this in a standalone file that both codes can access. So script 1 updates this variable like
if(single press): variable=1
elif(double press): variable=2
then in fire.py you can poll the variable.
if(varaible==1): start/stop fire
elif(variable==2): stop/start fire
else: #throw error
I'm sure there are more efficient ways to do this, but this method should be the easiest to understand.
I am trying to create a program that scrapes a website for Islamic prayer times and then sounds an alarm when one of them is due. I have been successful so far for the coding part, but when it comes to GUI with Tkinter it has been a cumbersome task. My problem is when I am trying to show the times scraped in a simple window. It first lags and sometimes even never shows up and when it does it never shows the text and keeps showing the loading circle. What is the problem here?
#import libraries
from bs4 import BeautifulSoup
from urllib.request import urlopen
from datetime import datetime , timedelta
from os import popen
from time import sleep
from win10toast import ToastNotifier
from tkinter import *
#html parsing
manar = "http://almanar.com.lb/legacy/salat.php" #webpage
page = urlopen(manar)
soup = BeautifulSoup(page,"html.parser")
date_box = soup.find("h2")#("div" ,attrs = {"class":"time full-date"})#attribute needed
#getting times(part1)
today = date_box.text.strip()
#today = today.split(" ")
today = " ".join(today.split())
print(today)
#current time
now = datetime.now()
print("at: " + str(now))
#notifications
toaster = ToastNotifier()
#getting times(part2)
day_parts = ["prayer-time emsak","prayer-time fajer","prayer-time shorook","prayer-time dohor","prayer-time aser","prayer-time moghreb","prayer-time ishaa","prayer-time midnight", ]
prayer = []
for part in day_parts :
day_part = soup.find("div",attrs = {"class":part})
day_part = day_part.text.strip()
day_part = " ".join(day_part.split())
prayer.append(day_part)
prayer_times = []
for pray_time in prayer:
if prayer.index(pray_time) == 1:
pray_time = pray_time.split()[1:3]
prayer_time = ": ".join(pray_time)
elif prayer.index(pray_time) == len(prayer) - 1:
pray_time = pray_time.split()
word = " ".join(pray_time[:2])
prayer_time = word + ": " + pray_time[2]
else:
prayer_time = ": ".join(pray_time.split())
print(prayer_time)
prayer_times.append(prayer_time)
toaster.show_toast("Prayer Time:", prayer_time)
text_prayers = "{}\n{}\n{}\n{}\n{}".format(prayer_times[0],prayer_times[1],prayer_times[2],prayer_times[3],prayer_times[4])
#Sounding Adhan
seconds_hms = [3600, 60, 1]
now_seconds = sum([a*b for a,b in zip(seconds_hms, [now.hour, now.minute, now.second])])
times = []
for pnt in prayer_times:
lpnt = pnt.split()
if len(lpnt) == 3: #because midnight is 2 words
time = lpnt[2]
else:
time = lpnt[1]
times.append(time)
times_in_sec = []
for dpt in times: #dayparttime
adhan_time = [int(n) for n in dpt.split(":")]
dpts = sum([a*b for a,b in zip(seconds_hms,adhan_time)])
times_in_sec.append(dpts)
#msg box
root = Tk()
root.title("prayer times")
frm = Frame(root,bg="yellow")#,height= 20, width=30,)
txt = Text(frm,height= 10, width=20)
txt.insert(INSERT,text_prayers)
txt.pack()
ok = Button(root,text="ok", fg="green",command= root.destroy)
ok.pack(side="bottom")
frm.pack()
root.mainloop()
#main process
if __name__ == "__main__":
while True :
for tis in times_in_sec :
time_diff_seconds = tis - now_seconds
if time_diff_seconds < 0:
continue
elif time_diff_seconds == 0 :
print("praying time!")
popen("c://users//Dell//downloads//adhan.mp3")
toaster.show_toast("next adhan starts in : ","%s" %timedelta(seconds=time_diff_seconds))
elif time_diff_seconds > 0 :
print("next adhan starts in : %s" %timedelta(seconds=time_diff_seconds))
toaster.show_toast("next adhan starts in : ","%s" %timedelta(seconds=time_diff_seconds))
sleep(time_diff_seconds)
popen("c://users//Dell//downloads//adhan.mp3")
else:
print("this is a module")
When you put root.mainloop() in your code, this will control the window until you close it. Then it will continue with the next lines. So, whatever you insert after it won't be runned while the window is open.
You can change the root.mainloop() with these 3 equivalent lines. You can include them in your while True, and you can put them more than once (if you feel it's still laggy):
while True:
root.update()
root.update_idletasks()
Another thing that you should change is the usage of time.sleep(). During this function the window will lag, as it won't be updated with the lines above. You could try using tk.after():
tkinter.after(delay_ms, callback=None, *args)
Requests Tkinter to call function callback with arguments args after a delay of at least delay_ms milliseconds. There is no upper limit to how long it will actually take, but your callback won't be called sooner than you request, and it will be called only once. [archive.org]
So, in conclusion, the important thing in tkinter is to always run the mainloop(), or equivalent. This way your window will never lag.
I wrote the program below,
can = CAN("can0", bitrate=50000, listen_only=True, error_reporting=True)
while True:
msg = can.recv()
print "Msg: ", msg
But it only displays the standard S or Extended X flags even though when I run the command in Terminal to check the network activity, I can see that the error counter is increasing.
import can
import CAN
import time
import logging
#logging.basicConfig(level=logging.DEBUG)
print("Initializing Listener")
can1 = CAN('can0', bitrate=500000, listen_only=True, err_reporting=True)
#print "Bus is : ", can1.bus.get_can_bus()
can1.bus.set_filters(can_filters=[{"can_mask":0x7FF, "can_id":0x00000000, "extended":False}])
CAN_ERR_FLAG = 0x20000000
while 1:
msg = can1.recv()
if (msg.arbitration_id & CAN_ERR_FLAG) == CAN_ERR_FLAG:
print "Can Error Caught"
elif msg.is_error_frame:
print "Finally Error Frame"
How can I read the error-frames of the CAN-bus ?
Things work fine when I use commnad candump -e any,0:0,#FFFFFFFF
Use Python - 3
import binascii
channel_name = "vcan0"
socketID = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
# socketID.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_ERR_FILTER, 0x1FFFFFFF)
error = socketID.bind((channel_name,))
print(binascii.hexlify(socketID.recv(32)))
I would like to know in any way that i can run a function as a background process.
I have gone through reading threading but i am still unclear on how to implement it.
In my system , the scapy detection script run when i click on the Button.But then the system will be hang as the scapy function is running.
What i want to achieve is that when i click on the button that initiate the scapy detection script , i would like to be able to do other function in the same system.(general idea was to prevent the system from hang)
def startMonitor(self,event):
selectedInterface = self.interfaces_cblist.GetValue()
#selectInterfaceStr = str(selectedInterface)
if len(selectedInterface) == 0:
noInterfaceSelected = wx.MessageDialog(None,"Please select an interface","",wx.ICON_ERROR)
noInterfaceSelected.ShowModal()
else:
#confirmMonitor = wx.MessageDialog(None,"Monitoring Start on %s interface"%selectedInterface,"",wx.OK)
#confirmMonitor.ShowModal()
x = selectedInterface
thread.start_new_thread(self.camtableDetection(x))
def camtableDetection(self,a):
global interface
interface = str(a)
THRESH=(254/4)
START = 5
def monitorPackets(p):
if p.haslayer(IP):
hwSrc = p.getlayer(Ether).src
if hwSrc not in hwList:
hwList.append(hwSrc)
delta = datetime.datetime.now() - start
if((delta.seconds > START) and ((len(hwList)/delta.seconds) > THRESH)):
camAttackDetected = wx.MessageDialog(None,"Cam Attack Detected","",wx.ICON_ERROR)
camAttackDetected.ShowModal()
hwList = []
start = datetime.datetime.now()
sniff(iface=interface,prn=monitorPackets)