Open a file in wordpad using python - ms-word

Is there a way to open a word file using wordpad (not MS word)? I can use win32com.client to open doc file using MS word like this:
word = win32.gencache.EnsureDispatch('Word.Application')
word.Visible = True
Not sure how to do this using wordpad. Is there any way to do this?

Ok I could get this working using subprocess:
import subprocess as sp
sp.Popen([programName, fileName])

pf = os.getenv("ProgramFiles")
subprocess.call([pf + "\\Windows NT\\Accessories\\wordpad.exe",filename])

Related

Python 3.7 pdflatex filenotfounderror

I am using python 3.7 with PyCharm on Windows 10. I have a Tex file and want to generate a pdf with pdflatex.
pdfl = PDFLaTeX.from_texfile('test.tex')
pdf, log, completed_process = pdfl.create_pdf(keep_pdf_file=True, keep_log_file=True)
I keep receiving the following error: FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\myusername\AppData\Local\Temp\tmps48h0jgi\file.pdf'
The program tries to find a certain file.pdf in my user folder in a temp folder.
(Texlive and TexStudio is also installed and working.)
What am I doing wrong?
Thanks.
Just specify where your .tex file is located.
def tex_pdf():
current_path = os.path.dirname(os.path.dirname(__file__))
media_folder = os.path.join(current_path, 'media/')
with open(f'{media_folder}tex/sometexfile.tex', 'w') as file:
file.write('\\documentclass{article}\n')
file.write('\\begin{document}\n')
file.write('Hello Palo Alto!\n')
file.write('\\end{document}\n')
pdfl = PDFLaTeX.from_texfile(f'{media_folder}tex/sometexfile.tex')
pdf = pdfl.create_pdf(keep_pdf_file=True, keep_log_file=False)

python close mdf(.mf4) file

I read a mf4 file using asammdf package. I want to delete this file after doing some edits but failed. The error shows: This file is in use by another program and cannot be accessed by the process. I wonder how to close a mf4 file before delete.
from asammdf import MDF
mdf = MDF(path)
from asammdf import MDF
mdf = MDF(path)
# .... something something
mdf.close()

Crystal report export to excel : unable to read file

I am using vb6 program to export a crystal report to excel sheet.After running the program the exported excel sheet is unreadable. getting the error "Unable to read file"
CrxRep.DiscardSavedData
CrxRep.ExportOptions.DestinationType = crEDTDiskFile
CrxRep.ExportOptions.FormatType = crEFTExcel97
'Input parameter set
CrxRep.ExportOptions.DiskFileName = DestName
CrxRep.ExportOptions.ExcelExportAllPages = True
CrxRep.EnableParameterPrompting = False
CrxRep.ExportOptions.ExcelUseWorksheetFunctions = True
CrxRep.ExportOptions.ExcelUseTabularFormat = True
CrxRep.ExportOptions.ExcelPageBreaks = True
CrxRep.ExportOptions.ExcelTabHasColumnHeadings = True
CrxRep.Export False
However this problem occurs only on production server.When I tried to export in dev server it works fine.
From where are you trying to read the file ?
If you are logged onto the server and can't read it, that suggests that Excel or perhaps ADO is not installed on the server, but you can answer that by looking at the icon. If windows recognizes the file type and shows you the Excel icon, then Excel is installed there.
If Excel is installed there, then copy the file to your desktop, or to the dev server, and try to open it there. If it opens there...the problem is likely a missing component ( perhaps ADO ) on the prod server.

IPython Notebook: Open/select file with GUI (Qt Dialog)

When you perform the same analysis in a notebook on different data files, may be handy to graphically select a data file.
In my python scripts I usually implement a QT dialog that returns the file-name of the selected file:
from PySide import QtCore, QtGui
def gui_fname(dir=None):
"""Select a file via a dialog and return the file name.
"""
if dir is None: dir ='./'
fname = QtGui.QFileDialog.getOpenFileName(None, "Select data file...",
dir, filter="All files (*);; SM Files (*.sm)")
return fname[0]
However, running this function from an notebook
full_fname = gui_fname()
causes the kernel to die (and restart):
Interestingly, puttying this 3 command in 3 separate cells works
%matplotlib qt
full_fname = gui_fname()
%matplotlib inline
but when I put those commands in one single cell the kernel dies again.
This prevents to create a function like gui_fname_ipynb() that transparently allows selecting a file with a GUI.
For convenience, I created a notebook illustrating the problem:
Open/select file with GUI (Qt Dialog)
Any suggestion on how to execute a dialog for file selection from within an IPython Notebook?
Using Anaconda 5.0.0 on windows (Python 3.6.2, IPython 6.1.0), the following two options are both working for me.
OPTION 1: Entirely in a Jupyter notebook:
CELL 1:
%gui qt
from PyQt5.QtWidgets import QFileDialog
def gui_fname(dir=None):
"""Select a file via a dialog and return the file name."""
if dir is None: dir ='./'
fname = QFileDialog.getOpenFileName(None, "Select data file...",
dir, filter="All files (*);; SM Files (*.sm)")
return fname[0]
CELL 2:
gui_fname()
This is working for me but it seems a bit...fragile. If I combine these two things into the same cell, it crashes. Or if I omit the %gui qt, it crashes. If I "restart kernel and run all cells", it doesn't work. So I kinda like this other option...
MORE RELIABLE OPTION: Separate script that opens dialog box in a new process
(Based on mkrog code here.)
PUT THE FOLLOWING IN A SEPARATE PYTHON SCRIPT CALLED blah.py:
from sys import executable, argv
from subprocess import check_output
from PyQt5.QtWidgets import QFileDialog, QApplication
def gui_fname(directory='./'):
"""Open a file dialog, starting in the given directory, and return
the chosen filename"""
# run this exact file in a separate process, and grab the result
file = check_output([executable, __file__, directory])
return file.strip()
if __name__ == "__main__":
directory = argv[1]
app = QApplication([directory])
fname = QFileDialog.getOpenFileName(None, "Select a file...",
directory, filter="All files (*)")
print(fname[0])
...AND IN YOUR JUPYTER NOTEBOOK
import blah
blah.gui_fname()
I have a universal code where it does its job without any problem. Here is my sugestion:
try:
from tkinter import Tk
from tkFileDialog import askopenfilenames
except:
from tkinter import Tk
from tkinter import filedialog
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filenames = filedialog.askopenfilenames() # show an "Open" dialog box and return the path to the selected file
print (filenames)
hope it can be useful
This behaviour was a bug in IPython:
https://github.com/ipython/ipython/issues/4997
that was fixed here:
https://github.com/ipython/ipython/pull/5077
The function to open a gui dialog should work on current master and on the oncoming 2.0 release.
To date, the last 1.x version (1.2.1) does not include a backport of the fix.
EDIT: The example code still crashes IPython 2.x, see this issue.

how to execute a command in scala?

I want to execute this command "dot -Tpng overview.dot > overview.png ", which is used to generate an image by Graphviz.
The code in scala:
Process(Seq("dot -Tpng overview.dot > overview.png"))
It does not work.
And I also want to open this image in scala. I work under Ubuntu. By default, images will be opened by image viewer. But I type "eog overview.png" in terminal, it reports error
** (eog:18371): WARNING **: The connection is closed
Thus, I do not know how to let scala open this image.
Thanks in advance.
You can't redirect stdout using > in command string. You should use #> and #| operators. See examples in process package documentation.
This writes test into test.txt:
import scala.sys.process._
import java.io.File
// use scala.bat instead of scala on Windows
val cmd = Seq("scala", "-e", """println(\"test\")""") #> new File("test.txt")
cmd.!
In your case:
val cmd = "dot -Tpng overview.dot" #> new File("overview.png")
cmd.!
Or just this (since dot accepts output file name as -ooutfile):
"dot -Tpng overview.dot -ooverview.png".!