So basically I am trying to open an image and then close it after few seconds with time.sleep.
First I tried using
import Image
import time
myImage = Image.open("C:\\Users\\User\\Desktop\\image.jpg")
myImage.show()
time.sleep(5)
but this didn't work out well, since the image didn't even open because Windows Photo Viewer couldn't find the file. However when I use webbrowser.open like this
import webbrowser
webbrowser.open('C:\\Users\\User\\Desktop\\image.jpg')
webbrowser.close()
it successfully opens the file in Windows Photo Viewer, but closing doesn't seem to work. It gives me the following error:
AttributeError: 'module' object has no attribute 'close'
I've been searching for 2 days now with no working solution. The image is .jpg incase that matters. Also I don't want to change my default image viewer or modify things that other people who use this would have to modify as well. Using Python 2.7.
Any help would be very much appreciated!
This is my way to do it in windows_xp_sp3.
import os, time
pic=["C:\\19.jpg","C:\\20.jpg","C:\\21.jpg","C:\\22.jpg"]
for p in pic:
os.startfile(p)
time.sleep(3)
os.system("taskkill /IM rundll32.exe")
Or, try this:
import subprocess, time
pic=["C:\\19.jpg","C:\\20.jpg","C:\\21.jpg","C:\\22.jpg","C:\\23.jpg","C:\\24.jpg","C:\\25.jpg","C:\\26.jpg","C:\\27.jpg"]
for p in pic:
r=subprocess.Popen(p,shell=True)
time.sleep(3)
# r.kill() #It won't work, because "shell=True" is set.If you need to kill the "subprocess",just don't use it.
Like This:
import os,subprocess, time
pic=["C:\\19.jpg","C:\\20.jpg","C:\\21.jpg","C:\\22.jpg","C:\\23.jpg","C:\\24.jpg","C:\\25.jpg","C:\\26.jpg","C:\\27.jpg"]
for p in pic:
r=subprocess.Popen(["rundll32.exe","shimgvw.dll,ImageView_Fullscreen",p])
time.sleep(3)
r.kill()
You are on the wrong track here, to close it you would have to instruct the browser to close that tab, or window, or whatever.
The way to instruct a browser to do that, is not standardized, and the same holds for something which is different for each browser, or indeed for each photo viewer.
If you want to control both opening and closing of a photo, you are better off doing that from within your Python program, instead of calling upon a different program such as a browser.
Related
I am new to pyton and i want to prank my friends by make a specific picture to pop up. I have set up everything up but I don't understand how to open a picture link, like in javascript (I think). Any solution to this problem is acceptable!
Your question is very confusing and it is more on the "can you code this for me" rather than you showing a problem you are having.
Nevertheless, a solution would be the following:
import os
from PIL import Image,ImageFont,ImageDraw
import time
import psutil
filedir=os.path.dirname(os.path.abspath(__file__))
while True:
picture=Image.open(filedir+'/picture_name.jpeg')
draw = ImageDraw.Draw(picture)
picture.show()
time.sleep(30)
peicture.close()
for proc in psutil.process_iter():
if proc.name() == "display":
proc.kill()
time.sleep(1200)
Now obviously for this you need to have the picture locally saved and know the path to it.
If you want to load one from the internet then I assume you could use
import urllib.request
url = urllib.request.urlopen('URL')
Or something of that form. I have never tried it.
I am using PIL to open a single image in the default image viewer:
from PIL import Image
img = Image.open('example.jpg')
img.show()
Does any Python module contain a function enabling opening multiple images in the current system's default image viewer? For instance when on OS X, Preview.app should open with the list of images in the sidebar. From the command line this is no problem at all:
$ open my_picture_number_*
Use case is that users should just be able to explore a few dozen images.
Use subprocess.run to run the operating system's default image viewing app. subprocess.run works a lot like a command line. You just need to know what the command is for the operating system you're on. For windows, "explorer" will do; for OS X, as you point out, it's "open." I'm not sure what it is for Linux, maybe "eog"?
So, your code would look like this:
import sys
import subprocess
def openImage(path):
imageViewerFromCommandLine = {'linux':'xdg-open',
'win32':'explorer',
'darwin':'open'}[sys.platform]
subprocess.run([imageViewerFromCommandLine, path])
I've tried to use #jgfoot's answer, which worked, but made my program hang after the viewer was launched. I've solved this issue by using subprocess.Popen instead, like this:
import sys
import subprocess
def openImage(path):
imageViewerFromCommandLine = {'linux':'xdg-open',
'win32':'explorer',
'darwin':'open'}[sys.platform]
subprocess.Popen([imageViewerFromCommandLine, path])
I'm trying to learn how to build a web browser bot as half learning half project for someone else and I've hit a snag.
The site I'm using as guide has:
def main():
pass
Which he claims keeps the shell window open do he can run various functions like get x,y cords of the mouse position and take screen shots.
However when I run my code exactly as he has it in the guide it immediately opens and closes.
What I don't want is something like, "make it so pressing enter closes shell instead", what needs to happen is the window stays open so I can enter various functions.
What am I doing wrong? Am I suppose to just import the code in a different shell and run the functions outside it?
The code:
import os
import time
import ImageGrab
x_pad = 0
y_pad = 61
def screenGrab():
box = (x_pad,y_pad,x_pad+1919,y_pad+970)
im = ImageGrab.grab(box)
im.save(os.getcwd() + '\\full_snap__' + str(int(time.time())) + '.png','PNG')
def main():
pass
if __name__ == '__main__':
main()
The guide is: http://code.tutsplus.com/tutorials/how-to-build-a-python-bot-that-can-play-web-games--active-11117
You have three ways:
Start the intepreter with the -i option, as suggested by Ulrich in the comments:
python -i my-script.py
This way, the interpreter will be left open as soon as your script finishes execution and a prompt will be shown.
Use pdb. This is often used for debugging, and has a different interface than the usual Python prompt. If you're not familiar with it, it might not be the best option in your case. Replace pass with these two lines:
import pdb
pdb.set_trace()
Use code. This will give you an interface much more similar to the usual Python shell and can be an alternative to pdb if you're not familiar with it:
import code
code.interact()
By the way, you were not doing anything wrong per se. The pass statement is not meant to "halt Python and start a prompt", it's just needed as a filler for functions or loops with an empty body.
I want to open a website in my local computer's web browser (Chrome or Internet Explorer) using Python.
open("http://google.co.kr") # something like this
Is there a module that can do this for me?
The webbrowser module looks promising: https://www.youtube.com/watch?v=jU3P7qz3ZrM
import webbrowser
webbrowser.open('http://google.co.kr', new=2)
From the doc.
The webbrowser module provides a high-level interface to allow
displaying Web-based documents to users. Under most circumstances,
simply calling the open() function from this module will do the right
thing.
You have to import the module and use open() function. This will open https://nabinkhadka.com.np in the browser.
To open in new tab:
import webbrowser
webbrowser.open('https://nabinkhadka.com.np', new = 2)
Also from the doc.
If new is 0, the url is opened in the same browser window if possible.
If new is 1, a new browser window is opened if possible. If new is 2,
a new browser page (“tab”) is opened if possible
So according to the value of new, you can either open page in same browser window or in new tab etc.
Also you can specify as which browser (chrome, firebox, etc.) to open. Use get() function for this.
As the instructions state, using the open() function does work, and opens the default web browser - usually I would say: "why wouldn't I want to use Firefox?!" (my default and favorite browser)
import webbrowser as wb
wb.open_new_tab('http://www.google.com')
The above should work for the computer's default browser. However, what if you want to to open in Google Chrome?
The proper way to do this is:
import webbrowser as wb
wb.get('chrome %s').open_new_tab('http://www.google.com')
To be honest, I'm not really sure that I know the difference between 'chrome' and 'google-chrome', but apparently there is some since they've made the two different type names in the webbrowser documentation.
However, doing this didn't work right off the bat for me. Every time, I would get the error:
Traceback (most recent call last):
File "C:\Python34\programs\a_temp_testing.py", line 3, in <module>
wb.get('google-chrome')
File "C:\Python34\lib\webbrowser.py", line 51, in get
raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser
To solve this, I had to add the folder for chrome.exe to System PATH. My chrome.exe executable file is found at:
C:\Program Files (x86)\Google\Chrome\Application
You should check whether it is here or not for yourself.
To add this to your Environment Variables System PATH, right click on your Windows icon and go to System. System Control Panel applet (Start - Settings - Control Panel - System). Change advanced settings, or the advanced tab, and select the button there called Environment Varaibles.
Once you click on Environment Variables here, another window will pop up. Scroll through the items, select PATH, and click edit.
Once you're in here, click New to add the folder path to your chrome.exe file. Like I said above, mine was found at:
C:\Program Files (x86)\Google\Chrome\Application
Click save and exit out of there. Then make sure you reboot your computer.
Hope this helps!
Actually it depends on what kind of uses. If you want to use it in a test-framework I highly recommend selenium-python. It is a great tool for testing automation related to web-browsers.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.python.org")
I think it should be
import webbrowser
webbrowser.open('http://gatedin.com')
NOTE: make sure that you give http or https
if you give "www." instead of "http:" instead of opening a broser the interprete displays boolean OutPut TRUE.
here you are importing webbrowser library
I had this problem.When I define firefox path my problem had been solved.
import webbrowser
urL='https://www.python.org'
mozilla_path="C:\\Program Files\\Mozilla Firefox\\firefox.exe"
webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(mozilla_path))
webbrowser.get('firefox').open_new_tab(urL)
You can simply simply achieve it with any python module that gives you an interaction with command line(cmd) like subprocess, os, etc.
but here I came up with examples on only two modules.
Here is syntax (command) cmd /c start browser_name "URL"
Example
import os
# or open with iexplore
os.system('cmd /c start iexplore "http://your_url"')
# or open with chrome
os.system('cmd /c start chrome "http://your_url"')
__import__('subprocess').getoutput('cmd /c start iexplore "http://your_url"')
You can also run the command in the cmd it will work to or use other module call
click which mainly used for writing command line utilities.
here is how
import click
click.launch('http://your_url')
Its a 2 liner! :D
You are a great programmer so never give up!
#Use web-browser.
import webbrowser as w
w.open("https://google.com")
#remember to include https://
#If you want to make a page open if you click a button do this :
from tkinter import *
#^ Imports tk
import webbrowser as w
#^ Imports wb
x = Tk()
#Makes main window
def clicked() :
w.open("https://google.com")
#Defined the click function. (We'll use this later.)
link = Button(x, text="Click Me!", command=clicked)
link.pack(pady=20, padx=20)
#Our button
x.mainloop()
#Tkinter mainloop
If you want to open a specific browser (e.g. Chrome and Chromium) with command line options like full screen or kiosk mode and also want to be able to kill it later on, then this might work for you:
from threading import Timer
from time import sleep
import subprocess
import platform
# Hint 1: to enable F11 use --start-fullscreen instead of --kiosk, otherwise Alt+F4 to close the browser
# Hint 2: fullscreen will only work if chrome is not already running
platform_browser = {
'Windows': r'"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk http://stackoverflow.com',
'Linux' : ['/usr/bin/chromium-browser', '--kiosk', 'http://stackoverflow.com']
}
browser = None
def open_browser():
global browser
platform_name = platform.system()
if platform_name in platform_browser:
browser = subprocess.Popen(platform_browser[platform_name])
else:
print(":-(")
Timer(1, open_browser).start() # delayed start, give e.g. your own web server time to launch
sleep(20) # start e.g. your python web server here instead
browser.kill()
If you want to open any website first you need to import a module called "webbrowser". Then just use webbrowser.open() to open a website.
e.g.
import webbrowser
webbrowser.open('https://yashprogrammer.wordpress.com/', new= 2)
How can my Python script get the URL of the currently active Google Chrome tab in Windows? This has to be done without interrupting the user, so sending key strokes to copy/paste is not an option.
First, you need to download and install pywin32. Import these modules in your script:
import win32gui
import win32con
If Google Chrome is the currently active window, first get the window handle by:
hwnd = win32gui.GetForegroundWindow()
(Otherwise, find the Google Chrome window handle by using win32gui.FindWindow. Windows Detective is handy when finding out class names for windows.)
It seems the only way to get the URL is to get the text in the "omnibox" (address bar). This is usually the tab's URL, but could also be any partial URL or search string that the user is currently typing.
Also, the URL in the omnibox won't include the "http://" prefix unless the user has typed it explicitly (and not yet pressed enter), but it will in fact include "https://" or "ftp://" if those protocols are used.
So, we find the omnibox child window inside the current Chrome window:
omniboxHwnd = win32gui.FindWindowEx(hwnd, 0, 'Chrome_OmniboxView', None)
This will of course break if the Google Chrome team decides to rename their window classes.
And then we get the "window text" of the omnibox, which doesn't seem to work with win32gui.GetWindowText for me. Good thing there's an alternative that does work:
def getWindowText(hwnd):
buf_size = 1 + win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0)
buf = win32gui.PyMakeBuffer(buf_size)
win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, buf)
return str(buf)
This little function sends the WM_GETTEXT message to the window and returns the window text (in this case, the text in the omnibox).
There you go!
Christian's answer did not work for me as internal structure of Chrome changed entirely and you can't really access elements of Chrome window using win32gui anymore.
The only possible way I managed to find was through UI Automation API, which has this python wrapper with some examples of usage
Run this and switch to Chrome window you want to grab address from:
from time import sleep
import uiautomation as automation
if __name__ == '__main__':
sleep(3)
control = automation.GetFocusedControl()
controlList = []
while control:
controlList.insert(0, control)
control = control.GetParentControl()
if len(controlList) == 1:
control = controlList[0]
else:
control = controlList[1]
address_control = automation.FindControl(control, lambda c, d: isinstance(c, automation.EditControl) and "Address and search bar" in c.Name)
print address_control.CurrentValue()
I quite new to StackOverFlow so apologies if the comment is out of tone.
After looking at :
Selenium,
launching chrome://History directly,
doing some keyboard emulation : copy/paste with Pywinauto,
trying to use SOCK_RAW connections to capture the headers as per the Network tab of the DevTool (this one was very interesting),
trying to get text of the omnibus/searchBar window element,
closing and reopening chrome to read the history tables,
....
I resulted in copy/pasting the History file itself (\AppData\Local\Google\Chrome\User Data\Default\History) into my application folder when the title of the window (retrieved using the hwnd + win32) is missing from "my" urls table.
This can be done even if the sqlite db is locked and does not interfere with the user experience.
Very basic solution that requires : sqlite3, psutil, win32gui.
Hope that helps.