I want to figure out whether a file is open in Notepad and a File open on Adobe Reader.
If you open task manager, Go to process tab, You can see the "Command Line" column (If not, then Go to View->Select Column) which contains EXE path and opened file's path.
If I get this information, I can easily parse this string to get opened file name (Along with it's path -- Bonus!)
I found an article, which shows the way by PowerShell using WMI. Is there any way to do the same using Python 2.7
I know there's a WMI library for python but not able to figure out how to implement:
Get-CimInstance Win32_Process -Filter "name = 'notepad.exe'" | fl *
I found a way using psutil
import psutil
for pid in psutil.pids():
p = psutil.Process(pid)
if p.name() == "notepad.exe":
print p.cmdline()
Related
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]
I can open a PDF file from within Python using subprocess.Popen() but I am having trouble closing the PDF file. How can I close an open PDF file using Python. My code is:
# open the PDF file
plot = subprocess.Popen('open %s' % filename, shell=True)
# user inputs a comment (will subsequently be saved in a file)
comment = raw_input('COMMENT: ')
# close the PDF file
#psutil.Process(plot.pid).get_children()[0].kill()
plot.kill()
Edit: I can close the PDF immediately after opening it (using plot.kill()) but this does not work if there is another command between opening the PDF and 'killing' it. Any help would be great - thanks in advance.
For me, this one works fine (inspired by this). Perhaps, instead of using 'open,' you can use a direct command for the PDF reader? Commands like 'open' tend to make a new process and then shut down immediately. I don't know your environment or anything, but for me, on Linux, this worked:
import subprocess
import signal
import os
filename="test.pdf"
plot = subprocess.Popen("evince '%s'" % filename, stdout=subprocess.PIPE,
shell=True, preexec_fn=os.setsid)
input("test")
os.killpg(os.getpgid(plot.pid), signal.SIGTERM)
On windows/mac, this will probably work if you change 'evince' to the path of the executable of your pdf reader.
I want to open a new cmd window and stream some text output (logs) while my python script is running (this is basically to check where I am in the script)
I can't find w way to do it and keep it open and stream my output.
Here is what I have now:
import os
p = os.popen("start cmd", mode='w')
def log_to_cmd(process, message):
p.write(message)
for i in range(10):
log_to_cmd(p, str(i))
And I want to get 0 to 9 output on the same cmd window already open.
Thanks a lot for any suggestion.
use Baretail this software allows you to stream logs.
If you want to stick to cmd shell I'd suggest installing something like GNU Utilities for Win32. It has most favourites, including tail. tail which allows you to open file like a log veiwer .
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.
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.