Is it possible to get the generated source code (so including JavaScript added DOM nodes) with Python and WebKit, and if so, how?
import webkit
web_view = webkit.WebView()
web_view.open('http://google.com')
But then?
Bind a function to the loadFinished(bool) signal, in that function you can use mainFrame().toHtml() to get the source code.
I found how to do it here: http://blog.motane.lu/2009/06/18/pywebkitgtk-execute-javascript-from-python/
Related
The idea is to clear the output of the python REPL provided by pyscript, embedded in a website.
I have tried the regular ways used in the OS console (os.system("clear"), print("\033c") and similar), but they don't work.
I have not found anything in the documentation of the py-repl or py-terminal elements.
A possible approach is to implement a function in python that uses the js module provided by pyscript to modify the DOM (see How to perform DOM manipulation using pyscript).
So a simplified version of my solution would look like this:
<py-script>
from js import document as _DOC
def clear():
ter = _DOC.getElementById("my-terminal")
ter.innerHTML = ''
</py-script>
Put this code before your REPL and now you can execute the clear() function from it and the terminal will be cleared.
I'm writing a Python script to toggle the "Hidden Items" status of the Windows Explorer. It changes the value of Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Hidden, but for the change to take effect all instances of the Explorer have to be refreshed.
I implemented the same idea a few months ago with AutoHotkey, there I could solve the refresh problem with the following commands I found on the AutoHotkey Forum:
WinGetClass, CabinetWClass
PostMessage, 0x111, 28931, , , A
PostMessage, 0x111, 41504, , , A
I tried different approaches to translate it, but wasn't able to get it working with Python. While searching for an answer I also found a solution with C# (Refresh Windows Explorer in Win7), which is far more complicated than the AutoHotkey version. I could let the Python script call the C# script, but I would much prefer a solution without auxiliary files.
How can I implement such behavior with Python?
Using pywin module:
import win32con
import win32gui
# List for handles:
handles = []
def collect_handles(h, _):
' Get window class name and add it to list '
if win32gui.GetClassName(h) == 'CabinetWClass':
handles.append(h)
def refresh_window(h):
' Send messages to window '
win32gui.PostMessage(h, win32con.WM_COMMAND, 28931, None)
win32gui.PostMessage(h, win32con.WM_COMMAND, 41504, None)
# Fill our list:
win32gui.EnumWindows(collect_handles, None)
# Perform action on our handles:
list(map(refresh_window, handles))
I was looking for some time, but still can't find any documented way to call python functions from GnomeShell extension code. Is there any possibility to do that?
You can do it like this :)
const Util = imports.misc.util;
let python_script = '/path/to/python/script';
Util.spawnCommandLine("python " + python_script);
I don't know how to directly call a python function from Gnomeshell, but there is an alternative way. As gnomeshell is programmed with Javascript you could use a python to javascript compiler to translate the python functions you need.
Just as the title says. I want to write a script that behaves differently depending on whether it's running inside a console window or in IDLE. Is there an object that exists only when running in IDLE that I can check for? An environment variable?
I'm using Python 2.6.5 and 2.7 on Windows.
Edit:
The answers given so far work. But I'm looking for an official way to do this, or one that doesn't look like a hack. If someone comes up with one, I'll accept that as the answer. Otherwise, in a few days, I'll accept the earliest answer.
I would prefer to do:
import sys
print('Running IDLE' if 'idlelib.run' in sys.modules else 'Out of IDLE')
Google found me this forum post from 2003. With Python 3.1 (for win32) and the version of IDLE it comes with, len(sys.modules) os 47 in the command line but 122 in the IDLE shell.
But why do you need to care anyway? Tkinter code has some annoyances when run with IDLE (since the latter uses tkinter itself), but otherwise I think I'm safe to assume you shouldn't have to care.
I suggest packing all the code in one function (Python 3):
def RunningIntoPythonIDLE():
import idlelib.PyShell
def frames(frame = sys._getframe()):
_frame = frame
while _frame :
yield _frame
_frame = _frame.f_back
return idlelib.PyShell.main.__code__ in [frame.f_code for frame in frames()]
So tkinter apps can do its check:
if not RunningIntoPythonIDLE():
root.mainloop()
I'm a touch late, but since IDLE replaces the standard streams with custom objects (and that is documented), those can be checked to determine whether a script is running in IDLE:
import sys
def in_idle():
try:
return sys.stdin.__module__.startswith('idlelib')
except AttributeError:
return True
My suggestion is to get list of all running frames and check if main Idle method would be in there.
def frames(frame = sys._getframe()):
_frame = frame
while _frame :
yield _frame
_frame = _frame.f_back
import idlelib.PyShell
print(idlelib.PyShell.main.func_code in [frame.f_code for frame in frames()])
the frames function generates frames running at moment of its declaration, so you can check if idle were here.
Looking for help/tutorials/sample code of using python to listen to distributed notifications from applications on a mac. I know the py-objc lib is the bridge between python and mac/cocoa classes, and the Foundation library can be used to add observers, but looking for examples or tutorials on how to use this to monitor iTunes.
If anyone comes by to this question, i figured out how to listen, the code below works. However accessing attributes do not seem to work like standard python attribute access.
Update: you do not access attributes as you would in python i.e (.x), the code has been updated below, it now generates a dict called song_details.
Update3: Update to the code, now subclassing NSObject, removed adding the addObserver from the class. Will keep the code updated on github, no more updates here.
import Foundation
from AppKit import *
from PyObjCTools import AppHelper
class GetSongs(NSObject):
def getMySongs_(self, song):
song_details = {}
ui = song.userInfo()
for x in ui:
song_details[x] = ui.objectForKey_(x)
print song_details
nc = Foundation.NSDistributedNotificationCenter.defaultCenter()
GetSongs = GetSongs.new()
nc.addObserver_selector_name_object_(GetSongs, 'getMySongs:', 'com.apple.iTunes.playerInfo',None)
NSLog("Listening for new tunes....")
AppHelper.runConsoleEventLoop()
The source code for GrowlTunes might give you some clues here. You'd have to translate from Objective-C to PyObjC, but eh, whatever. :)
GrowlTurnesController.m
(Or grab the whole growl source tree and navigate to GrowlTunes so you can see it all in action.: here's a link to the directions on how to get the source