how to quit os application with win32com in python - operating-system

import os
import win32com.client as win32
excel = win32.Dispatch("Excel.Application")
os.startfile(r'C:\asdf.xlsx') ## open excel file
print(excel.Workbooks.Count) ## ==0
excel.Quit() ## nothing happen
import os
import win32com.client as win32
excel = win32.Dispatch("Excel.Application")
excel.Workbooks.Open(r'C:\asdf.xlsx') ## open excel file
print(excel.Workbooks.Count) ## ==1
excel.Quit() ## is work

Related

How to pass extra argument to python unittest?

I want to pass library location while running unittest command. As I have to import library for using. Suppose the library name is some_lib . Same library will be executed on Linux as well as Windows.
Using python version 3.7.11
Used command : python3 -m unittest test_file.py lib_location
Details of test file.
import sys
sys.path.append(sys.argv[1]) # Hard code of path works fine.
import some_lib
import unittest
class TestCasesForSerializePy(unittest.TestCase):
#classmethod
def setUpClass(self):
self.archive_handler = some_lib.open('./test.archive')
def test_existing_archive(self):
self.assertTrue(self.archive_handler.isOpen())
if __name__ == '__main__':
# unittest.main(argv = [sys.argv[0]])
# sys.argv.pop()
unittest.main()
Error: ModuleNotFoundError: No module named 'C:/REC_158/build/lib'
Tried different approach as available on google.
Approach 1:
sys.argv.pop()
unittest.main()
Approach 2:
del sys.argv[1:]
unittest.main()
Approach 3:
unittest.main(argv=[sys.argv[0]]

How do you embed an ipython console with exec_lines?

I'm trying to embed an ipython console into my command line application.
I have the following:
import IPython
from traitlets.config import Config
c = Config()
c.InteractiveShellApp.exec_lines = [
'import matplotlib.pyplot as plt',
'%matplotlib',
]
return IPython.start_ipython(config=c, user_ns=globals())
However, it seems to completely ignore the "exec_lines" part since plt is not available.
See: Can you specify a command to run after you embed into IPython?
IPython.start_ipython(config=c, user_ns=locals())

How come the same py file runs in one Pycharm project, but not another, while both projects have same module imported

Recently, I installed pandas_profiling for the purpose of a particular project I created in the PyCharm IDE. It worked after having updated 'External tools' in Settings. Realising a similar need in another project context I did the installation of pandas_profiling in …\venv\Scripts path for that particular project as well. Did similar update of External tools in the new project. Yet the console keeps telling me that it cannot detect the module. Both projects have the pandas_profiling package files in the 'site packages' and 'venv' directories when I check. Any ideas out there? Thx, for your kind support.
from pathlib import Path
import pandas as pd
import numpy as np
import requests
import pandas_profiling
if __name__ == "__main__":
file_name = Path("C:\\Users\…..csv")
if not file_name.exists():
data = requests.get(
"C:\\Users\…..csv"
)
file_name.write_bytes(data.content)
df = pd.read_csv(file_name)
df["Feature_1"] = pd.to_datetime(df["Feature_1"], errors="coerce")
# Example: Constant variable
# df["source"] = "name of org"
# Example: Boolean variable
df["boolean"] = np.random.choice([True, False], df.shape[0])
# Example: Mixed with base types
df["mixed"] = np.random.choice([1, "A"], df.shape[0])
# Example: Highly correlated variables
df["Feature_2"] = df["Feature_2"] + np.random.normal(scale=5, size=(len(df)))
# Example: Duplicate observations
duplicates_to_add = pd.DataFrame(df.iloc[0:10])
duplicates_to_add[u"Feature_1"] = duplicates_to_add[u"Feature_1"]
df = df.append(duplicates_to_add, ignore_index=True)
profile = df.profile_report(
title="Report", correlation_overrides=["recclass"]
)
profile.to_file(output_file=Path("C:\\Users.....html"))
Response from console in new project (while working in existing project):
Traceback (most recent call last):
File "C:/Users/.../PycharmProjects/.../Pandas_Profiling_2.py", line 8, in <module>
import pandas_profiling
ModuleNotFoundError: No module named 'pandas_profiling'
Process finished with exit code 1

Open a file in wordpad using python

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])

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.