sys.exit() GCP Cloud Function - python

Have written GCP Cloud Function in Python 3.7. While executing, sys.exit() I'm getting 'A server error occurred ...'. I need to exit out of the function and have written following code.
import sys
if str(strEnabled) == 'True':
printOperation = "Operation: Enabling of user"
else:
sys.exit() #Exit From the Program
Please suggest, what I'm missing here.

Use return instead of sys.exit
Copied from bigbounty's comment

If you are calling a function from another function and needs to directly exit from the inner function without return you can use abort.
abort will directly return the response and exit the program from the place you are calling it.
import sys
from flask import abort
if str(strEnabled) == 'True':
printOperation = "Operation: Enabling of user"
else:
# abort(200) #return 200
abort(500, description="Exit") #return 500
Note: cloud functions use flask module internally, so you need not
install it separately.

Related

Checking network connection and running a program based off result

I am writing a program that will test for an active network connection, then run our software downloader if there is. If there is an update ready to download in the downloader it will automatically download and install said update.
import urllib3
from subprocess import Popen
import subprocess
def run_downloader():
return subprocess.Popen(['C:\ProgramFiles\PrecisionOSTech\Education\POSTdownloader.exe'])
def internet_on():
if urllib3.urlopen('http://216.58.192.142', timeout=1):
return True
else:
urllib3.URLError
return False
if internet_on == True:
run_downloader()
The expectation is to have the program test for an active connection and return either true or false. If true, then it should run the downloader.
Currently, the program runs with no errors but does not run the downloader upon completion. I can only imagine that the internet_on(): method is not returning true as I am wanting. If I run the subprocess.Popen line outside of the method, the downloader will start as planned.
Any assistance is appreciated !
Thanks
It should be something like this:
import urllib.request
from subprocess import Popen
import subprocess
def run_downloader():
return subprocess.Popen(['C:\ProgramFiles\PrecisionOSTech\Education\POSTdownloader.exe'])
def ispageresponding():
response_status_code = urllib.request.urlopen("http://www.stackoverflow.com").getcode()
return response_status_code == 200:
if __name__ == '__main__':
if ispageresponding() == True:
run_downloader()
Note that internet connection function is called in the if statement and is not inside the same function. Also if you are using python3 you should use urllib.request lib.

Flask API - Auto Exit

i am making an Flask-API for my project and i want to achieve something when the server restarts or runs, meaning whenever the main block is executed i want to do a check.
the code:
if __name__ == '__main__':
try:
with open('x.p','rb') as pkl_PR:
ps=pickle.load(pkl_PR)
with open('y.p','rb') as pkl_df:
df=pickle.load(pkl_df)
with open('z.p','rb') as pkl_spl:
spl_df = pickle.load(pkl_spl)
except Exception as e:
logger.debug(e)
app.run(debug=True)
so if any one of the pickle file doesn't exist, i dont want to start the server and save a log file with error.
so how do i go about it?
You can call sys.exit() from inside the except block, that will cause your program to exit before starting the flask server.

predefined python function failing to run with if name = main

I'm a beginner programmer and my goal is to design a utility that can accept an sms command and run a corresponding function on my main pc remotely. I'm using a variety of tools to do this (IFTTT, Dropbox, Twilio, Task Scheduler), but I've run into a little trouble along the way.
Most recently I've tried running the main code through a function which I've named 'main()'. However, when I attempt to call the function, command line throws an error:
Traceback (most recent call last):
File "C:\Python_Files\WIP\Check.py", line 104, in <module>
main()
NameError: name 'main' is not defined
I will post my code here for context (some info is edited for security):
#DESCRIPTION:
#Check if C:/Users/Thermaltake/Dropbox/Remote_Control contains a .txt file
#set count to corresponding integer
#delete file
#call function of corresponding integer
#reset count
#Set Task Scheduler to run this program every 5 minutes when idle.
import os
import time
import subprocess
import sys
import collections
import webbrowser
import logging
from twilio.rest import Client
#Twilio Account Info
account_sid = 'id'#not included for security
auth_token = 'token'#not included for security
client = Client(account_sid, auth_token)
myTwilioNumber = '+myTwilioNumber'#not included for security
myCellPhone = '+MyCellPhone'#not included for security
##FUNCTIONS##
#shutdown command
def shutdown():
os.system('shutdown -s')
#restart command
def restart():
os.system('shutdown -r')
#wake up computer and launch core programs
def wakeup():
subprocess.Popen('C:/Users/Thermaltake/AppData/Roaming/Spotify/Spotify.exe')
webbrowser.open('https://us-mg6.mail.yahoo.com/neo/launch')
webbrowser.open('https://www.rescuetime.com/dashboard')
#Launch main coding applications
def code():
webbrowser.open('http://somafm.com/player/#/now-playing/groovesalad')
subprocess.Popen('C:\Windows\system32\cmd.exe')
subproces.Popen('C:\Python_Files\Sublime Text 3\sublime_text.exe')
#Launch Remote Desktop and automatically log in
def logmein():
def main(): #main code
x=0 #counter
#checks for txt file in Remote_Control folder and assigns value to x
if os.path.isfile('C:/Users/Thermaltake/Dropbox/Remote_Control/shutdown.txt')==True:
x=1
elif os.path.isfile('C:/Users/Thermaltake/Dropbox/Remote_Control/wakeup.txt')==True:
x=2
elif os.path.isfile('C:/Users/Thermaltake/Dropbox/Remote_Control/restart.txt')==True:
x=3
elif os.path.isfile('C:/Users/Thermaltake/Dropbox/Remote_Control/code.txt')==True:
x=4
else:
print('No File Found')
#Checks x value and executes function
if x==1:
os.remove('C:/Users/Thermaltake/Dropbox/Remote_Control/shutdown.txt')
shutdown()
#print('Shutdown')#Placeholder for testing
message = client.messages.create(body='Shutdown Initiated', from_=, to=)#not included for security
elif x==2:
os.remove('C:/Users/Thermaltake/Dropbox/Remote_Control/wakeup.txt')
wakeup()
#print ('Spotify') #Placeholder. Define function to wake up PC and launch core programs
message = client.messages.create(body='Waking Up', from_=, to=)#not included for security
elif x==3:
os.remove('C:/Users/Thermaltake/Dropbox/Remote_Control/restart.txt')
restart()
#print ('Restart') #Placeholder.
message = client.messages.create(body='Restart Initiated', from_=, to=)#not included for security
elif x==4:
os.remove('C:/Users/Thermaltake/Dropbox/Remote_Control/code.txt')
code()
print('Happy Coding!')
message = client.messages.create(body='Ready to Code!', from_=, to=)#not included for security
else:
print ('No command entered')
#End Sequence (prints value and resets counter)
print (x)
x=0
os.system('pause') #Placeholder for testing
if __name__ == '__main__': #Runs main function
main()
'''
TODO:
Twilio not yet working. try different iterations of body and message. try assigning it to its own function
subprocess failing to launch programs. research alternatives. SMTP is a possibility.
possibly need to add Enter keystroke to the end of shutdown() and restart(). maybe even log in to log off.
add 'send to-do list to phone' function.
cleanup indentation and remove unnecessary modules
add 'flvto' function
add 'remote in' function.
+ Version 1.1 7/6/17 +
WORKING:
subprocess.Popen('C:\Windows\system32\cmd.exe')
webbrowser.open('http://somafm.com/player/#/now-playing/groovesalad')
os.remove
wakeup()
NOT WORKING:
subproces.Popen('C:\Python_Files\Sublime Text 3\sublime_text.exe')
Twilio return message
Task Scheduler: "Check_Dropbox on Lock"
BUGS:
IFTTT is buggy and sometimes unresponsive
Task Scheduler to check file is too slow. Need something faster. (Possibly 'Watch 4 Folder')
shutdown() waits til logon to initialize.
restart() waits til logon to initialize.
'''
Any help would be enormously appreciated. Keep in mind I have no formal education in CS, but I'm just trying to get my feet wet before starting a CS major this fall. I've only been programming for about 3 months.
also, if anything in this code can be done more elegantly, I will happily take advice.
-Jake
remove main() from inside logmein() so its in the global scope. The error you are getting is because when you call main from the global scope it isn't defined.

Python BackgroundScheduler program crashing when ran from another module

I am trying to build a application that will run a bash script every 10 minutes. I am using apscheduler to accomplish this and when i run my code from terminal it works like clock work. However when i try to run the code from another module it crashes i suspect that the calling module is waiting for the "schedule" module to finish and then crash when that never happens.
Error code
/bin/bash: line 1: 13613 Killed ( python ) < /tmp/vIZsEfp/26
shell returned 137
Function that calls schedule
def shedual_toggled(self,widget):
prosessSchedular.start_background_checker()
Schedule Program
def schedul_check():
"""set up to call prosess checker every 10 mins"""
print "%s check ran" %(counter)
counter =+ 1
app = prosessCheckerv3.call_bash() < calls the bash file
if app == False:
print "error with bash"
return False
else:
prosessCheckerv3.build_snap_shot(app)
def start_background_checker():
scheduler = BackgroundScheduler()
scheduler.add_job(schedul_check, 'interval', minutes=10)
scheduler.start()
while True:
time.sleep(2)
if __name__ == '__main__':
start_background_checker()
this program simply calls another ever 10 mins. As a side note i have been trying to stay as far away from multi-threading as possible but if that is required so be it.
Well I managed to figure it out my self. The issue that GTK+ is not thread safe so the timed module need to be either be ran in another thread or else you can realise/enter the thread before/after calling the module.
I just did it like this.
def shedual_toggeld(self,widget):
onOffSwitch = widget.get_active()
""" After main GTK has logicly finished all GUI work run thread on toggel button """
thread = threading.Thread(target=self.call_schedual, args=(onOffSwitch,))
thread.daemon = True
thread.start()
def call_schedual(self, onOffSwitch):
if onOffSwitch == True:
self.sch.start_background_checker()
else:
self.sch.stop_background_checker()
This article goes through it in more detail. Hopefully some one else will find this useful.
http://blogs.operationaldynamics.com/andrew/software/gnome-desktop/gtk-thread-awareness

main function in django web service

I am preparing a web service using django in python. When I start web service, I would like to have a main function to run. However, code below did not work in web service. I want to have an initializer function which will fill the structures defined global. I can achieve it by directly defining an init function and call it end of the module but I don't know whether this is the proper way of doing so.
if __name__ == '__main__':
main()
Here similar question was posted. As I understand there is no clear solution for that and I find my way to do this. I defined a dummy function in web service module like:
def warmup(request):
response = HttpResponse()
response.write("ok")
return response
We start application with command sudo python manage.py runserver 0.0.0.0:8081 so I add a piece of code in manage.py such that:
#!/usr/bin/env python
import os
import sys
import requests
import threading
import time
def warmup_request():
print "warmup.."
time.sleep(1)
try:
r = requests.get("http://localhost:8081/warmup/")
if r.content == "ok":
return
except Exception, e:
pass
threading.Timer(0,warmup_request).start()
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
from django.core.management import execute_from_command_line
warmup_request()
execute_from_command_line(sys.argv)
If warmup service API returns ok it means loading initial data process has finished. By defining a global flag, we can block all other service API requests before warming up has finished. Or instead defining global flag we may use request_started signal stated here to block all incoming requests with more little effort.

Categories