I'm currently able to take a screenshot of my desktop using this code
from PIL import Image, ImageGrab
x =ImageGrab.grab()
x.show()
but the problem is, this captures the python script/idle dialog(box) which is running the script as well.
I want to take a clean screenshot of my desktop screen, caputuring all the desktop icons,background screen and taskbar etc via a script.
Is there a way to automate it so the script can automatically do this?
Thanks.
One of the solutions would be to use a Python web server (tornado or whatever).
Take a look at the following code (Python 3 version):
pip install tornado
from PIL import ImageGrab
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
x = ImageGrab.grab()
x.show()
self.write("Hello, world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
Minimise the IDLE window when the script is running.
Open a browser from your phone or another computer and navigate to:
http://[your IP address]:8888
I cannot test this script because ImageGrab.grab() only works on Mac and Windows but unfortunately not on Linux.
I tried out this code:
from PIL import ImageGrab
import time
import cv2
time.sleep(5)
x = ImageGrab.grab()
x.save('Screenshot.jpg')
x.show()
I delayed the execution of ImageGrab.grab() by 5 seconds, in the meantime I minimized my workspace and switched to my Desktop. After 5 seconds it captured a screenshot of my desktop and saved it.
I am still figuring out a way to automatically capture the Desktop.
Related
I have a script with ArcGIS using arcpy model. And I want to combine it with Django. The script runs on console successfully, however, when running with Django, I find the arcpy functions do not run. So I make a simple test for it, and get the same result.
test.py
import arcpy
import os
def test_arcpy():
tempFolder = arcpy.env.scratchFolder
tempGDBPath = os.path.join(tempFolder, 'test.gdb')
arcpy.env.overwriteOutput = True
if not arcpy.Exists(tempGDBPath):
arcpy.AddMessage('create..')
arcpy.CreateFileGDB_management(tempFolder, 'test.gdb')
return arcpy.Exists(tempGDBPath)
views.py
from django.http import HttpResponse
from . import test
def t(request):
msg = str(test.test_arcpy())
return HttpResponse(msg)
If I run the test.py in console, it return True.But if I run it in django, it always return false. If I cannot solve it , I cannot make more difficult script in django. Can you help me?
I found the similar question in Flask app with ArcGIS, Arcpy does not run, but no solution in this question.
I think I can use the subprocess model to run the arcpy script in console, and then return the console message back to the django function.
But I really want to know whether arcpy can run with django or not.
i meet the same problem the same as you in Flask.
I check the source code in arcpy, found there is an bug in arcgisscripting.pyd file while i trigger arcpy.Exists() from Flask. And i lost any clew. After searching for some case on ESRI online blog, i certainly found that it's a bug in arcpy. So i advice u:
try higher version arcpy.(my current version is 10.1)
try to run your code in a console
try to run message queue like from multiprocessing import Queue, Process
try to not use the function. In my case, I avoid to use arcpy.Exists()
try to use 64-bit arcpy in arcServer.
Like this. What API should I use to show this box?
update:
I successed in sublime-text 3,but failed in sublime-text 2.Do you know why?
The code is:
import sublime, sublime_plugin
class CCAutoComplete(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
flag = sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS
result = ([["abv","abv"],["abcd123","abcd"]],flag)
return result
The auto-completion panel can be manually populated with the on_query_completions listener.
To view a functioning example of it's implementation:
Install PackageResourceViewer
Run PackageResourceViewer: Open Resource from the command palette
Select the CSS package and open css_completions.py
I am using scrapy to crawl some websites with JavaScript. The scraper works fine, but it keeps freezing at random places. I need to kill the script with ctrl+z, but it only freezes when i use this downloader middleware:
from scrapy.http import Request, FormRequest, HtmlResponse
import gtk
import webkit
import jswebkit
class WebkitDownloader( object ):
def process_request( self, request, spider ):
if( type(request) is not FormRequest ):
webview = webkit.WebView()
webview.connect( 'load-finished', lambda v,f: gtk.main_quit() )
webview.load_uri( request.url )
gtk.main()
js = jswebkit.JSContext( webview.get_main_frame().get_global_context() )
renderedBody = str( js.EvaluateScript( 'document.documentElement.innerHTML' ) )
return HtmlResponse( request.url, body=renderedBody )
I tried debugging the script by printing every single step of the middleware, but it runs fine. It freezes when i see this in the terminal:
Message: console message: http://www.myurl.com/js/Shop.min.js?twsv=20140521122711 #642: JQMIGRATE: Logging is active
I tried different middlewares and download handlers, but it always freezes. I also checked my connection, but i cant see any patterns or signs of interruption. I am using the latest version of scrapy.
2014-04-25 - Update
When i do get it to run a couple of minutes, i get this error:
Creating pipes for GWakeup: Too many open files
GLib-ERROR **: Creating pipes for GWakeup: Too many open files
2014-05-27 - Update
I ran "print" through every line of code in my middleware. It turns out it freezes the code and terminal randomly when it comes to the gtk.main() part. When I use the lsof command during a "freeze" i can see a bunch of "scrapy" "files" open. After a freeze my code wont run again until i reset my computer. I guess there is some kind of bug that causes a leakage.
I have been studying multiprocessing module in Python for few days.
However, I have met a strange problem that I cannot resolve it.
The source code is very simple but I cannot get any results after running this code.
The code is as follows:
import multiprocessing as multi
def worker():
print "Worker!!!"
return
jobs = []
for i in range(5):
p = multi.Process(target = worker)
jobs.append(p)
p.start()
I was expecting to get a five time of printing "Worker!!!".
However, the only thing I've got is
* Remote Interpreter Reinitialized *
">>>"
">>>"
Does anybody who has a idea to solve this problem??
Please DO HELP ME!!!
According to multiprocessing documentation:
Note
Functionality within this package requires that the __main__
module be importable by the children. This is covered in Programming
guidelines however it is worth pointing out here. This means that some
examples, such as the multiprocessing.Pool examples will not work in
the interactive interpreter.
...
Safe importing of main module
Make sure that the main module can be safely imported by a new Python
interpreter without causing unintended side effects (such a starting a
new process).
...
one should protect the “entry point” of the program by using if
__name__ == '__main__'
So your program should read as follow:
import multiprocessing as multi
def worker():
print "Worker!!!"
if __name__ == '__main__':
jobs = []
for i in range(5):
p = multi.Process(target = worker)
jobs.append(p)
p.start()
for job in jobs:
job.join()
There are a few topics on this, but none with a satisfactory answer.
I have a python application running in an IPython qt console
http://ipython.org/ipython-doc/dev/interactive/qtconsole.html
When I encounter an error, I'd like to be able to interact with the code at that point.
try:
raise Exception()
except Exception as e:
try: # use exception trick to pick up the current frame
raise None
except:
frame = sys.exc_info()[2].tb_frame.f_back
namespace = frame.f_globals.copy()
namespace.update(frame.f_locals)
import IPython
IPython.embed_kernel(local_ns=namespace)
I would think this would work, but I get an error:
RuntimeError: threads can only be started once
I just use this:
from IPython import embed; embed()
works better than anything else for me :)
Update:
In celebration of this answer receiving 50 upvotes, here are the updates I've made to this snippet in the intervening six years since it was posted.
First, I now like to import and execute in a single statement, as I use black for all my python code these days and it reformats the original snippet in a way that doesn't make sense in this specific and unusual context. So:
__import__("IPython").embed()
Given than I often use this inside a loop or a thread, it can be helpful to include a snippet that allows terminating the parent process (partly for convenience, and partly to remind myself of the best way to do it). os._exit is the best choice here, so my snippet includes this (same logic w/r/t using a single statement):
q = __import__("functools").partial(__import__("os")._exit, 0)
Then I can simply use q() if/when I want to exit the master process.
My full snippet (with # FIXME in case I would ever be likely to forget to remove it!) looks like this:
q = __import__("functools").partial(__import__("os")._exit, 0) # FIXME
__import__("IPython").embed() # FIXME
You can follow the following recipe to embed an IPython session into your program:
try:
get_ipython
except NameError:
banner=exit_msg=''
else:
banner = '*** Nested interpreter ***'
exit_msg = '*** Back in main IPython ***'
# First import the embed function
from IPython.frontend.terminal.embed import InteractiveShellEmbed
# Now create the IPython shell instance. Put ipshell() anywhere in your code
# where you want it to open.
ipshell = InteractiveShellEmbed(banner1=banner, exit_msg=exit_msg)
Then use ipshell() whenever you want to be dropped into an IPython shell. This will allow you to embed (and even nest) IPython interpreters in your code and inspect objects or the state of the program.