powerpoint.Quit() function not quitting Microsoft powerpoint in python-pptx.Is there any work around to quit - com

Since i m unable to quit powerpoint it is giving me problems to convert into pdf.I am using pywin32 227 version and python 3.6.1 64bit.Is there any function in python to release COM objects.I am working on this for weeks but i m stuck here without any progress.Please help mw if you know anything
def convert(files, formatType=32):
powerpoint = win32com.client.Dispatch("Powerpoint.Application")
powerpoint.Visible = 1
print("ppt",powerpoint)
for filename in files:
newname = os.path.splitext(filename)[0] + ".pdf"
deck = powerpoint.Presentations.Open(filename)
deck.SaveAs(newname, formatType)
deck.Close()
powerpoint.Quit()# NOT ABLE TO QUIT POWERPOINT
files = glob.glob(path)
print(files)
convert(files)
print("after entering files")
os.remove(path)

You can close the TASK this way:
import os
os.system('taskkill /F /IM POWERPNT.EXE')

Related

attach excel files to seperate email IDs from a folder

This is the below code to separate as per the requirement enter image description here
The code executes till the time of separating the files per country to excel, but the final mail attachment is not done due to this error 'com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Cannot find this file. Verify the path and file name are correct.', None, 0, -2147024894), None)
'
import os, datetime,pathlib,schedule
import csv
from time import sleep
import win32com.client as client
import win32com.client as win32 # pip install pywin32
from pathlib import Path
import os
import pickle
import win32com
from PIL import ImageGrab
workbook_path = r'C:\Users\cb\OneDrive\final.xlsx'
#C:\Users\cb\Desktop\Automate
EXCEL_FILE_PATH = Path.cwd() / "final_new.xlsx"
ATTACHMENT_DIR = Path.cwd() / "Attachments"
ATTACHMENT_DIR.mkdir(exist_ok=True)
data = pd.read_excel(workbook_path, sheet_name="Sheet1")
data.head()
# Query/Filter the data frame and export the filtered data frame as an Excel file
for unique_value in unique_values:
data_output = data.query(f"{column_name} == #unique_value")
output_path = ATTACHMENT_DIR / f"{unique_value}.xlsx"
data_output.to_excel(output_path, sheet_name=unique_value, index=False)
#EXCEL_FILE_PATH = r'C:\Users\cb\OneDrive\paste this as people.csv'
email_list = pd.read_excel('yeah.xlsx')
email_list.tail()
outlook = win32com.client.dynamic.Dispatch("outlook.Application")#.GetNameSpace("MAPI")
for index, row in email_list.iterrows():
mail = outlook.CreateItem(0)
mail.To = row["Email ID"]
mail.CC = row["CC"]
mail.Subject = f"issue is for Country - {row['COUNTRY']}"
mail.HTMLBody = f"""
Hi {row['Contact Name']},
Please find attached the report for {row['COUNTRY']}.
This is a Test email
Best Regards,
team Auto
"""
attachment_path = str(ATTACHMENT_DIR / f"{row['COUNTRY']}.xlsx")
mail.Attachments.Add(Source=attachment_path)
mail.Display()
'Exception occurred.', (4096, 'Microsoft Outlook', 'Cannot find this file. Verify the path and file name are correct.'
It seems the problem is related to attaching a file:
attachment_path = str(ATTACHMENT_DIR / f"{row['COUNTRY']}.xlsx")
mail.Attachments.Add(Source=attachment_path)
The Attachments.Add method creates a new attachment in the Attachments collection. The source of the attachment can be a file (represented by the full file system path with a file name) or an Outlook item that constitutes the attachment. You need to make sure that such file exists on the disk. Try to copy the result file path and open the file from the shell.

getting FindFailed issue in sikuli for image on windows server 2019 (ADO VM)

Getting below error when running script on window server 2019 (ADO VM) through pipeline , same script is working fine on windows 10 (having resolution 1920X1080).
I am using screen resolution utility to change the VM resolution to 1920X1080 in pipeline.
I am setup the path Bundle Folder by using below text:
ImagePath.setBundleFolder(new File(System.getProperty("user.dir")+"/SikuliImages"));
using below code
ImagePath.setBundleFolder(new File(System.getProperty("user.dir")+"/SikuliImages"));
System.out.println("Image Bundle Path="+ImagePath.getBundlePath());
Screen screen=new Screen();
String UserName_Image_Path = System.getProperty("user.dir")+"/SikuliImages/UserName_TextBox.png";
String UserPassword_Image_Path = System.getProperty("user.dir")+"/SikuliImages/UserPassword_TextBox.png";
String SignIn_Image_Path = System.getProperty("user.dir")+"/SikuliImages/SignIn_Button.png";
Pattern P_UserName = new Pattern(UserName_Image_Path);
Pattern P_UserPassword = new Pattern(UserPassword_Image_Path);
Pattern P_SignIn = new Pattern(SignIn_Image_Path);
System.out.println("Wait for popup");
screen.wait(P_UserName,30);
Match UserName_Found = screen.exists(UserName_Image_Path);
UserName_Found.highlight(2);
screen.type(P_UserName,UserName);
Match UserPassword_Found = screen.exists(UserPassword_Image_Path);
UserPassword_Found.highlight(2);
screen.type(P_UserPassword,UserPassword);
Match SignIn_Found = screen.exists(SignIn_Image_Path);
SignIn_Found.highlight(2);
screen.click(P_SignIn);
FindFailed : C:\agent\vsts-agent-win-x64-2.200.2_work\1\s\Automation/SikuliImages/UserName_TextBox.png: (378x54) in R[0,0 1920x1080]#S(0)
Line 2226, in file Region.java
Could someone help me please.
This is not valid windows path since it contains both \ and /

PowerPoint to PDF: Minimum size option

I was attempting to convert PowerPoint files to PDF using PowerShell and was able to do so. However, I am trying to take this one step further and select the 'Minimum Size (publishing online)' option through the script.
Is there a property that needs to be set for this to happen? I'm guessing it is the $ppQualityStandard variable but not exactly sure.
EDIT: This is what I am using currently:
function ppt_to_pdf ($folderpath, $pptname) {
Add-Type -AssemblyName office
$ppFormatPDF = 2
$ppQualityStandard = 0
$p = New-Object -ComObject PowerPoint.Application
$p.Visible = [Microsoft.Office.Core.MsoTriState]::msoTrue
$ppt = $p.Presentations.Open("$folderpath\$pptname")
$ppt.SaveCopyAs("$folderpath\$pptname", 32)
$ppt.Close()
$p.Quit()
$p = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()
}
I suspect you need to use .ExportAsFixedFormat rather than .SaveCopyAs.
It takes, among other parameters, Intent as type ppFixedFormatIntent, which can be either:
ppFixedFormatIntentScreen (=1)
or
ppFixedFormatIntentPrint (=2)
There's a host of other parms. To learn more, start PPT, go into the VBA IDE and press F2 for the Object Browser and search for ExportAsFixedFormat

How do I export PSDs as PNGs with py-appscript?

I wrote a script to export PSDs as PNGs with rb-appscript. That's fine and dandy, but I can't seem to pull it off in py-appscript.
Here's the ruby code:
#!/usr/bin/env ruby
require 'rubygems'
require 'optparse'
require 'appscript'
ps = Appscript.app('Adobe Photoshop CS5.app')
finder = Appscript.app("Finder.app")
path = "/Users/nbaker/Desktop/"
ps.activate
ps.open(MacTypes::Alias.path("#{path}guy.psd"))
layerSets = ps.current_document.layer_sets.get
# iterate through all layers and hide them
ps.current_document.layers.get.each do |layer|
layer.visible.set false
end
layerSets.each do |layerSet|
layerSet.visible.set false
end
# iterate through all layerSets, make them visible, and create a PNG for them
layerSets.each do |layerSet|
name = layerSet.name.get
layerSet.visible.set true
ps.current_document.get.export(:in => "#{path}#{name}.png", :as => :save_for_web,
:with_options => {:web_format => :PNG, :png_eight => false})
layerSet.visible.set false
end
And here's the apparently nonequivalent python code:
from appscript import *
from mactypes import *
# fire up photoshop
ps = app("Adobe Photoshop CS5.app")
ps.activate()
# open the file for editing
path = "/Users/nbaker/Desktop/"
f = Alias(path + "guy.psd")
ps.open(f)
layerSets = ps.current_document.layer_sets()
# iterate through all layers and hide them
for layer in ps.current_document.layers():
layer.visible.set(False)
#... and layerSets
for layerSet in layerSets:
layerSet.visible.set(False)
# iterate through all layerSets, make them visible, and create a PNG for them
for layerSet in layerSets:
name = layerSet.name()
layerSet.Visible = True
ps.current_document.get().export(in_=Alias(path + name + ".png"), as_=k.save_for_web,
with_options={"web_format":k.PNG, "png_eight":False})
The only part of the python script that doesn't work is the saving. I've gotten all sorts of errors trying different export options and stuff:
Connection is invalid... General Photoshop error occurred. This functionality may not be available in this version of Photoshop... Can't make some data into the expected type...
I can live with just the ruby script, but all of our other scripts are in python, so it would be nice to be able to pull this off in python. Thanks in advance internet.
Bert,
I think I have a solution for you – albeit several months later. Note that I'm a Python noob, so this is by no means elegant.
When I tried out your script, it kept crashing for me too. However by removing the "Alias" in the export call, it seems to be OK:
from appscript import *
from mactypes import *
# fire up photoshop
ps = app("Adobe Photoshop CS5.1.app")
ps.activate()
# open the file for editing
path = "/Users/ian/Desktop/"
f = Alias(path + "Screen Shot 2011-10-13 at 11.48.51 AM.psd")
ps.open(f)
layerSets = ps.current_document.layer_sets()
# no need to iterate
ps.current_document.layers.visible.set(False)
ps.current_document.layer_sets.visible.set(False)
# iterate through all layerSets, make them visible, and create a PNG for them
for l in layerSets:
name = l.name()
# print l.name()
l.visible.set(True)
# make its layers visible too
l.layers.visible.set(True)
# f = open(path + name + ".png", "w").close()
ps.current_document.get().export(in_=(path + name + ".png"), as_=k.save_for_web,
with_options={"web_format":k.PNG, "png_eight":False})
I noticed, too, that you iterate through all the layers to toggle their visibility. You can actually just issue them all a command at once – my understanding is that it's faster, since it doesn't have to keep issuing Apple Events.
The logic of my script isn't correct (with regards to turning layers on and off), but you get the idea.
Ian

ClearCase : list the content of a directory (ls) using CAL

In ClearCase, you can list the content of a directory using "cleartool ls".
My question is how can I do the same thing using CAL (ClearCase Automation Layer). The reason I prefer the COM API is because I won't have to parse the output of "ls".
So far, I am able to get the VOB and the View successfully, but I didn't find any method for listing the content.
My code so far:
IClearCase cc = new ApplicationClass();
CCVOB vob = cc.get_VOB("\\VOB-name");
CCView view = cc.get_View("ViewTag");
Thank you for your help.
I wrote VonC's answer in C# for those interrested.
string[] files = Directory.GetFiles("View path here", "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
try
{
CCVersion ver = cc.get_Version(file);
Console.WriteLine(ver.Path);
}
catch(Exception) {/*the file is not versioned*/}
}
May be this is a good start:
Set CC = Wscript.CreateObject("ClearCase.Application")
Set DirVer = CC.Version(".")
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Folder = FSO.GetFolder(DirVer.Path)
Wscript.Echo "Files under source control: "
For Each File in Folder.Files
On Error Resume Next
Set Ver = CC.Version(File.Name)
If Err.Number = 0 Then
Wscript.Echo Ver.ExtendedPath
End If
Next
The idea being to use ICCVersion methods to try accessing the version of a file. If it does not return an error, it is indeed a versioned file.
Now I know the file is versioned, how can I remove it (rmname).
Do not use RemoveVersion():
Removes irretrievably the version (equivalent to cleartool rmver)
WARNING! This is a potentially destructive operation. Because CAL does not prompt the user for input under any circumstances, there is no confirmation step when RemoveVersion is invoked. Invoking RemoveVersion is equivalent to running cleartool rmver with the -force option.
Instead use the RemoveName from the ICCElement interface.