Cron doesnt output anything from python script if selenium is run headless - python-3.x

I've got a WEIRD problem, I've been banging my head against this issue for the last 2 weeks, googling around and drinking to wash away the pain of my failures.
So here's the deal, when I run my alarm script from cron, nothing at all is redirected to my log file, and the script doesn't seem to function. HOWEVER, when I comment out a seemingly meaningless option in selenium, the logging works. The script functions perfectly when run outside of cron. I'm using non-sudo cron by the way, as that's where my python environment is set up.
The script basically gets some information and types it into a very nice TTS engine (natural reader) and plays it in the morning. I don't want to pay for a TTS or natural reader which is why I'm using selenium
CODE
Here is my cron script, I've ommited my other cron entries as they are not important:
#reboot sh scripts/YakScripts.sh -alarm > scripts/logs/alarm.log 2>&1
Here is my YakScripts.sh file, again, I've omitted the meat of it:
TZ=":America/New_York" date
export PYTHONPATH=${PYTHONPATH}:"scripts"
case "$1" in
-alarm) python3 scripts/Alarm/alarm.py ;;
*) echo "Thats not a function, dumbass."
;;
esac
Here is my alarm script:
import Alarm.Weather.getDailyForecast as weather
import Alarm.SunCycles.suncycles as suncycles
import TTS.speak as voice
from datetime import date
today = date.today()
# dd/mm/YY
naturalDate = today.strftime("%B %d, %Y")
print(naturalDate)
dayOfWeek = today.strftime("%A")
print(dayOfWeek)
alarmText = "Good Morning. \n"
alarmText += "Today is " + dayOfWeek + ". " + naturalDate + ".\n"
alarmText += weather.getMostRecentForecast() + "\n\n"
alarmText += "Today, the sun rises at " + suncycles.getSunrise() + ".\n"
alarmText += "and sets at " + suncycles.getSunset() + ".\n"
print(alarmText)
voice.speak(alarmText)
And lastly (and the most important bit) here is my speak script, I've removed most of this as I dont think naturalReader would like me posting this. But I tested and it functions the same:
import time
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import TTS.locators as locators
import globalData
selectedVoice = globalData.tts["voice"]
max_stale_tries = globalData.tts["max_retries"]
def speak(message):
options = Options()
#options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.get("https://www.naturalreaders.com/online/")
print("Loaded the web page")
time.sleep(3)
ISSUES
So with that, here's the problem, when I don't comment out the headless line in there (line 15 of speak.py) this is what my alarm.log file looks like:
Tue Feb 9 21:08:03 EST 2021
and when I comment out that line, this is what It looks like:
Tue Feb 9 21:27:43 EST 2021
February 10, 2021
Wednesday
Good Morning.
Today is Wednesday. February 10, 2021.
Tonight the forecast is Snow showers before 10pm, then snow showers and patchy freezing drizzle. Cloudy, with a low around 8. Wind chill values as low as -6. Northeast wind 8 to 12 mph.
Wednesday the forecast is Snow showers before 7am. Cloudy, with a high near 16. Wind chill values as low as -7. Northeast wind 10 to 14 mph, with gusts as high as 18 mph.
Today, the sun rises at 07:29 AM.
and sets at 06:12 PM.
Traceback (most recent call last):
File "../../../../../../../../scripts/Alarm/alarm.py", line 35, in <module>
voice.speak(alarmText)
File "/scripts/TTS/speak.py", line 16, in speak
driver = webdriver.Firefox(options=options)
File "/home/appa/.local/lib/python3.8/site-packages/selenium/webdriver/firefox/webdriver.py", line 170, in __init__
RemoteWebDriver.__init__(
File "/home/appa/.local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
self.start_session(capabilities, browser_profile)
File "/home/appa/.local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/home/appa/.local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/appa/.local/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Process unexpectedly closed with status 1
I know this error has to do with the webdriver not being able to connect to the display, which is why I need to be running this headless.
I'm really just wondering why in the world I get output when that line is uncommented, and DONT get output when run normally (headless).

Related

PyAlgoTrade: How to use resampleBarFeed with multiple instruments?

I am resampling a few instruments with [pyalogtrade][1].
I have a base barfeed for 1-minute data, which is working fine
I have added a resampler to resample for 2 minutes, as follows:
class Strategy(strategy.BaseStrategy):
def __init__(self, instruments,feed, brk):
strategy.BaseStrategy.__init__(self, feed, brk)
self.__position = None
self.__instrument = instruments
self._resampledBF = self.resampleBarFeed(2 * bar.Frequency.MINUTE, self.resampledOnBar_2minute)
self.info ("initialised strategy")
I got this error:
2022-09-08 12:36:00,396 strategy [INFO] 1-MIN: INSTRUMENT1: Date: 2022-09-08 12:35:00+05:30 Open: 17765.55 High: 17774.5 Low: 17765.35 Close: 1777 myStrategy.run()
File "pyalgotrade\pyalgotrade\strategy\__init__.py", line 514, in run
self.__dispatcher.run()
File "pyalgotrade\pyalgotrade\dispatcher.py", line 109, in run
eof, eventsDispatched = self.__dispatch()
File "pyalgotrade\pyalgotrade\dispatcher.py", line 97, in __dispatch
if self.__dispatchSubject(subject, smallestDateTime):
File "pyalgotrade\pyalgotrade\dispatcher.py", line 75, in __dispatchSubject ret = subject.dispatch() is True
File "pyalgotrade\pyalgotrade\feed\__init__.py", line 106, in dispatch
dateTime, values = self.getNextValuesAndUpdateDS()
File "pyalgotrade\pyalgotrade\feed\__init__.py", line 81, in getNextValuesAndUpdateDS
dateTime, values = self.getNextValues()
File "pyalgotrade\pyalgotrade\barfeed\__init__.py", line 101, in getNextValues
raise Exception(
Exception: Bar date times are not in order. Previous datetime was 2022-09-08 12:34:00+05:30 and current datetime is 2022-09-08 12:34:00+05:30
However, the error does not occur if the self._resampledBF = self.resampleBarFeed is commented out.
Also, on searching online, I found a similar report/ possible fix reported earlier on Google groups: https://groups.google.com/g/pyalgotrade/c/v9ht1Bfz5Ds/m/ojF8uH8sFwAJ
The solution recommended was:
Sorry never mind, I fixed it. Using current timestamp instead of the one from IB and that fixed it.
Not sure if this is has been resolved.
Would like to know how to resolve the error while resampling.

I am not able to call one python script from another script using os.system in Pycharm

My sample file in one project is:
import os
feature_name = 'neelam'
combo_boxes = {"'Primary CAN InterfaceComboBox": ["[CanSim, CanSim]", "best_match"],
"'Secondary CAN InterfaceComboBox": ["[CanSim, CanSim]", "best_match"],
"Seed Data SimulationComboBox": ["[Off, OFF]", "best_match"],
"Planter TypeComboBox": ["[_2160_FFT_24R30, 2160 Front Fold 24 Row 30 Inch]", "best_match"],
"BrandComboBox": ["[CaseIH, Case IH]", "best_match"],
"LATAM Gran Fertilizer InstalledComboBox": ["[Hydraulic, Hydraulic]", "best_match"],
"DiagnosticsComboBox": ["[On, ON]", "best_match"]}
for i in combo_boxes:
log_msg = 'Click on combo box {0} at {1}'.format(i, combo_boxes[i][0].split(",")[1][:-1])
print(log_msg)
Now I am trying to run sample file from another python script as given:
import os
script_string = r'C:\Neelam\Neelam_Dev\test_automation\FeatureTestScripts\Common\sample.py'
os.system(script_string)
But after running the second file, it is not printing the output of sample.py. It is just opening that file in Pycharm.

Convert user input to time which changes boolean value for the duration entered?

I'm working on this side project game to grasp python better. I'm trying to have the user enter the amount of time the character has to spend busy, then not allow the user to do the same thing until they have completed the original time entered. I have tried a few methods with varying error results from my noob ways. (timestamps, converting input to int and time in different spots, timeDelta)
def Gold_mining():
while P.notMining:
print('Welcome to the Crystal mines kid.\nYou will be paid in gold for your labour,\nif lucky you may get some skill points or bonus finds...\nGoodluck in there.')
print('How long do you wish to enter for?')
time_mining = int(input("10 Gold Per hour. Max 8 hours --> "))
if time_mining > 0 and time_mining <= 8:
time_started = current_time
print(f'You will spend {time_mining} hours digging in the mines.')
P.gold += time_mining * 10
print(P.gold)
P.notMining = False
End_Time = (current_time + timedelta(hours = 2))
print(f'{End_Time} time you exit the mines...')
elif time_mining > 8:
print("You can't possibly mine for that long kid, go back and think about it.")
else:
print('Invalid')
After the set amount of time i would like for it to change the bool value back to false so that you can mine again.
"Crystal Mining" is mapped to a different key for testing so my output says "Inventory" but would say "Crystal Mining" when it works properly and currently looks like this:
*** Page One ***
Intro Page
02:15:05
1 Character Stats
2 Rename Character
3 Inventory
4 Change Element
5 Menu
6 Exit
Num: 3
Welcome to the Crystal mines kid.
You will be paid in gold for your labour,
if lucky you may get some skill points or bonus finds...
Goodluck in there.
How long do you wish to enter for?
10 Gold Per hour. Max 8 hours --> 1
You will spend 1 hours digging in the mines.
60
Traceback (most recent call last):
File "H:\Python ideas\input_as_always.py", line 176, in <module>
intro.pageInput()
File "H:\Python ideas\input_as_always.py", line 45, in pageInput
self.pageOptions[pInput]['entry']()
File "H:\Python ideas\input_as_always.py", line 134, in Gold_mining
End_Time = (current_time + timedelta(hours = 2))
TypeError: can only concatenate str (not "datetime.timedelta") to str

Write date and variable to file

I am trying to write a variable and the date and time on the same line to a file, which will simulate a log file.
Example: July 25 2018 6:00 pm - Variable contents here
So far I am able to write the variable to the file but I am unsure how to use the datetime library or other similar libraries. Some guidance would be appreciated.
Below is the current script.
import subprocess
import datetime
var = "test"
with open('auditlog.txt', 'a') as logfile:
logfile.write(var + "\n")
The fastest way I found is doing something like this:
import time
var = time.asctime()
print(var)
Result: Thu Jul 26 00:46:04 2018
If you want to change the placements of y/m/d etc. you can alternatively use this:
import time
var = time.strftime("%B %d %Y %H:%M pm", time.localtime())
print(var)
Result: July 26 2018 00:50 pm
Have a look here.
By the way, is the subprocess intended in your code? You don't need it to open/write to files. Also you should do logfile.close() in your code after you wrote to it.

Stop time from saying 07 minutes and just 7 in Pyttsx3

import pyttsx3
import time
time = time.strftime("%M minutes past %I")
engine = pyttsx3.init()
engine.setProperty('rate',200)
engine.say("Hi Tom");
engine.say("The time is" + time);
engine.runAndWait();
When running this it will say "Hi Tom, the time is 07 minutes past 10" for example and will say a 0 in front of the minutes if its between 0-9 but 10-59 its says it normally. Is there a way to remove the 0 from being said?
Could this be useful
t = time.localtime()
...
engine.say('The time is %d minutes past %s' % (t.tm_min,t.tm_hour))

Resources