webbrowser.open() in python - python

I have a python file html_gen.py which write a new html file index.html in the same directory, and would like to open up the index.html when the writing is finished.
So I wrote
import webbrowser
webbrowser.open("index.html");
But nothing happen after executing the .py file. If I instead put a code
webbrowser.open("http://www.google.com")
Safari will open google frontpage when executing the code.
I wonder how to open the local index.html file?

Try specifying the "file://" at the start of the URL. Also, use the absolute path of the file:
import webbrowser, os
webbrowser.open('file://' + os.path.realpath(filename))

Convert the filename to url using urllib.pathname2url:
import os
try:
from urllib import pathname2url # Python 2.x
except:
from urllib.request import pathname2url # Python 3.x
url = 'file:{}'.format(pathname2url(os.path.abspath('1.html')))
webbrowser.open(url)

Related

Getting code from a .txt on a website and pasting it in a tempfile PYTHON

I was trying to make a script that gets a .txt from a websites, pastes the code into a python executable temp file but its not working. Here is the code:
from urllib.request import urlopen as urlopen
import os
import subprocess
import os
import tempfile
filename = urlopen("https://randomsiteeeee.000webhostapp.com/script.txt")
temp = open(filename)
temp.close()
# Clean up the temporary file yourself
os.remove(filename)
temp = tempfile.TemporaryFile()
temp.close()
If you know a fix to this please let me know. The error is :
File "test.py", line 9, in <module>
temp = open(filename)
TypeError: expected str, bytes or os.PathLike object, not HTTPResponse
I tried everything such as a request to the url and pasting it but didnt work as well. I tried the code that i pasted here and didnt work as well.
And as i said, i was expecting it getting the code from the .txt from the website, and making it a temp executable python script
you are missing a read:
from urllib.request import urlopen as urlopen
import os
import subprocess
import os
import tempfile
filename = urlopen("https://randomsiteeeee.000webhostapp.com/script.txt").read() # <-- here
temp = open(filename)
temp.close()
# Clean up the temporary file yourself
os.remove(filename)
temp = tempfile.TemporaryFile()
temp.close()
But if the script.txt contains the script and not the filename, you need to create a temporary file and write the content:
from urllib.request import urlopen as urlopen
import os
import subprocess
import os
import tempfile
content = urlopen("https://randomsiteeeee.000webhostapp.com/script.txt").read() #
with tempfile.TemporaryFile() as fp:
name = fp.name
fp.write(content)
If you want to execute the code you fetch from the url, you may also use exec or eval instead of writing a new script file.
eval and exec are EVIL, they should only be used if you 100% trust the input and there is no other way!
EDIT: How do i use exec?
Using exec, you could do something like this (also, I use requests instead of urllib here. If you prefer urllib, you can do this too):
import requests
exec(requests.get("https://randomsiteeeee.000webhostapp.com/script.txt").text)
Your trying to open a file that is named "the content of a website".
filename = "path/to/my/output/file.txt"
httpresponse = urlopen("https://randomsiteeeee.000webhostapp.com/script.txt").read()
temp = open(filename)
temp.write(httpresponse)
temp.close()
Is probably more like what you are intending

Open local HTML with parameters

I'm a python beginner and I want my code to open a local HTML page with parameters (e.g. /help/index.html#1). Right now I have the below code:
def openHelp(self, helpid):
import subprocess
import webbrowser
import sys, os
directory = os.getcwd()
if sys.platform == 'darwin': # For macOS
url = 'file://' + directory + '/help/index.html' + '#{}'.format(str(helpid))
webbrowser.get().open(url)
else:
url = 'help/index.html' + '#{}'.format(str(helpid))
webbrowser.open(url)
The code opens the webpage, however without the parameters (#helpid). Where did I make a mistake? Thanks in advance!
Your code looked fine to me. I tried it and it worked. You have to call it with openHelp("",1). The #helpid parameter was added correctly. Make sure it is a number.

Using python to run Latex compiler, why does it hang if there are errors in the latex?

I have a python script that takes the (latex source) content of a google doc and creates a pdf.
This is the function I use for the pdf:
# -*- coding: utf-8 -*-
#!/usr/bin/python
"""One of the main activiating files of IMPS - this downloads all the files in a directory, creates the input.tex file and archives them a tar file
TODO
Before we send to stackoverflow we should make sure that everthing is in a function and that the If __main__ trigger is working
I'd also like to have doc strings for all of the methods
"""
import os
import glob
import tarfile
import time
import datetime
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import urlparse
import argparse
import re
def generate_pdf(filename,destination=""):
"""
Genertates the pdf from string
from http://stackoverflow.com/q/19683123/170243
"""
import subprocess
import shutil
current = os.getcwd()
this_dir=os.path.dirname(os.path.realpath(__file__))
os.chdir(this_dir+"/latex")
proc=subprocess.Popen(['pdflatex',filename+'.tex'],stdout=subprocess.PIPE)
# subprocess.Popen(['pdflatex',tex])
temp=proc.communicate()
#Have to do it twice so that the contents pages are right
proc=subprocess.Popen(['pdflatex',filename+'.tex'],stdout=subprocess.PIPE)
temp=proc.communicate()
shutil.copy(filename+'.pdf',"../../live/"+destination+filename+ str(datetime.datetime.now()).replace(".", "-").replace(":", "_") + ".pdf")
trace_file = open("../../live/"+destination+"trace.txt", "w")
print >>trace_file, temp[0]
print >>trace_file, temp[1]
trace_file.close()
os.chdir(current)
Everything runs fine if the latex has NO errors, but if there is a problem, the function hands and nothing gets done. What I want is that problems are noted and exported into the trace. Any ideas what's going wrong?
When it encounters errors, pdflatex asks the user about how to proceed, so your script "hangs" because it is expecting input. Use pdflatex -interaction=nonstopmode -halt-on-error. See this TeX StackExchange question.
I think what you are missing is that you need to also need to setup a pipe for STDERR. This will let you see the error messages from pdflatex. You could also try explicitly setting the buffer size to zero when calling Popen.
self.child = subprocess.Popen(command
,bufsize=0
,stdout=subprocess.PIPE
,stderr=subprocess.PIPE)

Python : Function to pull a sound clip from URL and save it in local machine

Would like to create a function that pulls a sound from given url and saves it in my machine locally
use urllib module
import urllib
urllib.urlretrieve(url,sound_clip_name)
the file will be save as what you provide the name
alternative, using urllib2
import urllib2
file = urllib2.urlopen(url).read()
f = open('sound_clip','w')
f.write(file)
f.close()
don't forget to give the extension of your file
If in Python 2.7, urllib2 module is your friend, or urllib.request in Python3.
Example in 2.7 :
import urllib2
f = urllib2.urlopen('http://www.python.org/')
with open(filename, w) as fd:
fd.write(f.read)

How to open a list of address in browser

I have a list of links, which is stored in a file. I would like to open all the links in my browsers via some script instead of manually copy-pasting every items.
For example, OS: MAC OS X; Browser: Chrome; Script: Python (prefered)
Take a look at the webbrowser module.
import webbrowser
urls = ['http://www.google.com', 'http://www.reddit.com', 'http://stackoverflow.com']
b = webbrowser.get('firefox')
for url in urls:
b.open(url)
P.S.: support for Chrome has been included in the version 3.3, but Python 3.3 is still a release candidate.
Since you're on a mac, you can just use the subprocess module to call open http://link1 http://link2 http://link3. For example:
from subprocess import call
call(["open","http://www.google.com", "http://www.stackoverflow.com"])
Note that this will just open your default browser; however, you could simply replace the open command with the specific browser's command to choose your browser.
Here's a full example for files of the general format
alink
http://anotherlink
(etc.)
from subprocess import call
import re
import sys
links = []
filename = 'test'
try:
with open(filename) as linkListFile:
for line in linkListFile:
link = line.strip()
if link != '':
if re.match('http://.+|https://.+|ftp://.+|file://.+',link.lower()):
links.append(link)
else:
links.append('http://' + link)
except IOError:
print 'Failed to open the file "%s".\nExiting.'
sys.exit()
print links
call(["open"]+links)

Categories

Resources