save text file and display its content on the browser - python

If the following script.py writes "some text here" to output.txt file, my URL will be http://my_name/script.py. My question is, how can I read the output.txt as soon as (right after) the following function creates it, so that my URL reads like http://my_name/output.txt.
Many thanks in advance.
#------ script.py -------
def write_txt(){
f=('./output.txt', 'w')
f.write("some text here")
}

try webbrowser lib.
import webbrowser
myurl = "file:///mydir/output.txt"
webbrowser.open(myurl)
However:
Note that on some platforms, trying to
open a filename using this function,
may work and start the operating
system’s associated program.
That is: your file will probably be open in your default text editor (p.e. notepad). A possible solution is to give a custom extension to your file (p.e. output.url) and to associate the extension to your browser (not tested)

Depends on various factors, like OS and webserver used.
Pipe the output to the browser specifying a correct content-type, or, given you script writes to an accessible location, issue a HTTP redirect code pointing to that location.

Related

How to use the Open With feature with Python?

I'm currently working with a python script that has the following code. It opens a file that has JSON text and determines a value from that.
browseFiles()
def browseFiles():
global fileName
fileName = filedialog.askopenfilename(title = "Select a File", filetypes = (("All Files","*.*")))
# Open the File in Read Mode
fileFile = open(fileName, "r")
# Read the file
fileContent = fileFile.read()
# Render the JSON
fileJSON = json.loads(fileContent)
# Determine the ID
myID = fileJSON["key"]
# Update the Status
windowRoot.title(myID)
... remaining code
fileFile.close()
However, it is less convenient to open the program every time, and then navigate to it.
Windows has an 'Open With' feature in File Explorer where we can right-click a file and open it with apps such as Word, etc.
How to implement this in a Python script? Should I consider creating a .exe of this script first, and if yes then which library would be most suitable for this? (Considering it is a very small and simple utility)
Some extra information that is probably unwanted: I'm using Tkinter for the GUI.
(By the way, if this question already exists on StackOverFlow or any other website, then please comment the link instead of just marking it as duplicate. I tried searching a lot and couldn't find anything)
Regards,
Vivaan.
simple example:
import sys
try:
#if "open with" has been used
print(sys.argv[1])
except:
#do nothing
pass
usage example:
import sys
from tkinter import filedialog
filetypes = (('Text files', '*.txt'),('All files', '*.*'))
#if filename is not specified, ask for a file
def openfile(filename = ''):
#print contents of file
if filename == '':
filename = filedialog.askopenfilename(title='Open A File',filetypes=filetypes)
with open(filename,'r', encoding="utf-8") as file:
read = file.read()
print(read)
try:
#if "open with" has been used
openfile(filename = sys.argv[1])
except:
#ask for a file
openfile()
then compile it to exe with nuitka (or whatever tool you use),
and try it.
or (for testing, without having to compile it every time you make a change):
make a .bat file
#echo off
py program.py %*
pause
Then every time you want to run it,
you open with that file.
what you need is added new item into right click context menu.
You can take sample registry code below, modify the path to your py script C:\your_script.py and save it as anything end with .reg extension then double click to execute this registry file.
after that, you should see open with my_py when u right click on the target file
from your py script side, replace the filedialog code with fileName = sys.argv[1]
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\*\shell\open with my_py\command]
#="python C:\\your_script.py %1"
*** Please be cautious with the registry code as wrong registry hack can be troublesome
refer this for manually modify the registry
Found another question with answers that helped me. Posting this for other people who might find this question.
answer from Roy Cai:
My approach is to use a redirect .bat file containing python someprogram.py %1. The %1 passes the file path into the python script which can be accessed with
from sys import argv
argv[1]

Python: How to get the URL to a file when the file is received from a pipe?

I created, in Python, an executable whose input is the URL to a file and whose output is the file, e.g.,
file:///C:/example/folder/test.txt --> url2file --> the file
Actually, the URL is stored in a file (url.txt) and I run it from a DOS command line using a pipe:
type url.txt | url2file
That works great.
I want to create, in Python, an executable whose input is a file and whose output is the URL to the file, e.g.,
a file --> file2url --> URL
Again, I am using DOS and connecting executables via pipes:
type url.txt | url2file | file2url
Question: file2url is receiving a file. How do I get the file's URL (or path)?
In general, you probably can't.
If the url is not stored in the file, I seems very difficult to get the url. Imagine someone reads a text to you. Without further information you have no way to know what book it comes from.
However there are certain usecases where you can do it.
Pipe the url together with the file.
If you need the url and you can do that, try to keep the url together with the file. Make url2file pipe your url first and then the file.
Restructure your pipeline
Maybe you don't need to find the url for the file, if you restructure your pipeline.
Index your files
If only a certain files could potentially be piped into file2url, you could precalculate a hash for all files and store it in your program together with the url. In python you would do this using a dict where the key is the file (as a string) and the value is the url. You could use pickle to write the dict object to a file and load it at the start of your program.
Then you could simply lookup the url from this dict.
You might want to research how databases or search functions in explorers handle indexing or alternative solutions.
Searching for the file
You could use one significant line of the file and use something like grep or head on linux to search all files of your computer for this line. Note that grep and head are programs, not python functions. For DOS, you might need to google the equivalent programs.
FYI: grep searches for one line of text inside a file.
head puts out the first few lines of a file. I suggest comparing only the first few lines of files to avoid searching through huge file.
Searching all files on the computer might take very long.
You could only search files with the same size as your piped input.
Use url.txt
If file2url knows the location of the file url.txt, then you could look up all files in url.txt until you find a file identical to the file that was piped into your program. You could combine this with the hashing/ indexing solution.
'file2url' receives the data via standard input (like keyboard).
The data is transferred by the kernel and it doesn't necessarily have to have any file-system representation. So if there's no file there's no URL or path to that for you to get.
Let's try to do it by obvious way:
$ cat test.py | python test.py
import sys
print ''.join(sys.stdin.readlines())
print sys.stdin.name
<stdin>
So, filename is "< stdin>" because, for the python there is no filename - only input.
Another way is a system-dependent. Find a command line, which was used, for example, but no garantee that is will be works.

How to get python to read a file that has been opened through File Explorer?

I don't exactly know how to phrase this question, but I have tried my best.
Let's say I have an application and I have set it to be the default to run when the .example file extention has been double clicked within File Explorer. Now, how do I get this application not to just launch, but instead to react as if it has been asked to open the file. Now I know there is the:
file = open ("C:\\ExampleFolder\\ExampleFile.example)
file = file.read()
method of reading a file but how would I get the program to run this script when the program is launched by the opening of a file and in which way would I get the program to know the location of the opened file? I know that there are questions about setting a python app to the default but I have found nothing, if I am asking the question right, on completing the above on stackoverflow or a Google search. Or I am just looking at this wrong or asking the question wrong?
I'm not sure this might be what you are looking for. You can check whether, double clicking on a file with extension .example which you have linked to your program, means that an argument is passed to your program: the file name being opened. You can check whether this is the case by:
import sys
print sys.argv
#if that is meaningless, try printing every single argument passed to the script
#I can't recall whether len(sys.argv) is also = sys.argc!
for x in xrange(len(sys.argv)):
print sys.argv[x]
I hope this is of some help!

How can I store a .CHM Help File as text with Python?

I am using Pastebin to store the code of my python program to keep it updated on several computers. I am now trying to similarly maintain an updated help window. I saw that I could use .chm files to keep a full help dialog in a single file, but the files do not translate to text well.
I used a sample .chm file from Microsoft, I opened the file ("Viewhlp.chm") with notepad and copied the text to Pastebin, and then used the script below to attempt to recreate the .chm file. This does not work. It gives a "cannot open the file" message when opening directly and is simply ignored with PyWin32.
Is there another single file format for help dialogs that I can load with python?
import urllib2, sys
helpUrl = "http://pastebin.com/raw.php?i=a8rF2i8a"
originalPath = "Viewhlp.chm"
newPath = "NewHlp.chm"
try:
helpData = urllib2.urlopen(helpUrl)
except urllib2.URLError:
sys.exit()
currentHelp = helpData.read()
with open(newPath, mode="wb") as helpFile:
helpFile.write(currentHelp)
# briefly display using PyWin32 or just open the chm files directly
import win32help
win32help.HtmlHelp(0, None, win32help.HH_INITIALIZE, None)
link = win32help.HH_AKLINK()
link.indexOnFail = 1
link.url = ""
link.msgText = ""
link.msgTitle = ""
link.window = ""
win32help.HtmlHelp(0, originalPath, win32help.HH_KEYWORD_LOOKUP, link)
win32help.HtmlHelp(0, newPath, win32help.HH_KEYWORD_LOOKUP, link)
Notepad won't display the non-printing characters properly. Probably the easiest thing to do would be to base64 encode the .chm, then open the encoded version in notepad before you copy it to pastebin. Then unencode it when you read it:
currentHelp = base64.b64decode(helpData.read())
One way I convert things/documents like this is by installing a "Generic / Text Only" printer on my Windows system, and then selecting it and picking the "print to file" option in the printing dialog that appears when I try to print something from the associated application.
This results in a plain text file with what would have been printed in it. There's probably some way to automate it, although I've never tried.

reading output from a text file

For instance, the following test.py script can be displayed at ../cgi-bin/test.py, but is there a way I could display the same output from a text file (like test.txt) instead of text.py, so that the url would be something like ../text.txt?
--- test.py ---
def printxt():
print "Content-Type: text/plain"
print """my text here..."""
If you point your browser to www.yoursite.com/yourtext.txt, you'll discover that most browsers are fully capable of displaying text files without any additional code.
You appear to be asking if web servers can serve, and web browsers display text files. The answer is yes. Put the text file underneath DOCUMENTROOT and it's all good.
Or did I misunderstand the question?
If you want to use Python to do this in the context of a larger program (the example you just gave would be useless if that's all that you wanted it to do), you can simply use the standard:
file = open("filename.txt", "r")
for line in file:
print line
You already know about the Content-type line which of course would be the same.
If the file is small enough to be read into memory all at once without causing problems, you can use "print file.read()" in order to have file.read() read the entire file as a single string, then print that out.

Categories

Resources