how to convert python code into executable file - cmd

I have a python code that run perfect now i want to convert this code into an executable file .I am using python 3.6.
Until now I was able to convert it ,and make it run but the problem is that when the user try to run the .exe file cmd window is opened.
how can I make the cmd window to be hidden OR to not show?
the code below is to create the build folder that includes the converted executable file.
setup.py
import cx_Freeze
import sys
import os
import matplotlib
#os.environ['TCL_LIBRARY'] = "C:\\LOCAL_TO_PYTHON\\Python35-32\\tcl\\tcl8.6"
#os.environ['TK_LIBRARY'] = "C:\\LOCAL_TO_PYTHON\\Python35-32\\tcl\\tk8.6"
os.environ['TCL_LIBRARY'] = "C:\\EXECUTABLE_PROGRAMS\\Python3.6\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\EXECUTABLE_PROGRAMS\\Python3.6\\tcl\\tk8.6"
base = None
if sys.platform == 'win32':
base='Win32GUI'
executables = [cx_Freeze.Executable("myPDFviewer.py",base=None)]
cx_Freeze.setup(
name = "this is a test",
options = {"build_exe": {"packages":["numpy"],}},
version = "0.01",
descriptions = "Trying to get this to work",
executables = executables
)

Change base=None to base="Win32GUI"

Related

How to open an image in Python

I am new to python. I am learning how to add images to my Tkinter file. However, when I try to run the following code, the interpreter returns the error: FileNotFoundError: [Errno 2] No such file or directory: lee.jpg
I hypothesize that I need a more specific path and have already ensured that both the file and image are in the same folder. Any explanations would be appreciated.
from tkinter import *
from PIL import ImageTk, Image
#Main Window
window = Tk()
window.title("Join")
window.geometry("800x600")
window.configure(background='white')
path = "lee.jpg" # I believe this is causing issues
#Makes image Tkinter-compatible
img = ImageTk.PhotoImage(Image.open(path))
panel = Label(window, image=img)
panel.pack(side="bottom", fill="both", expand="yes")
#Start
window.mainloop()
This is actually pretty simple and can be achieved with the below:
from tkinter import * #imports tkinter
root = Tk() #establishes root as the Tk window
image = PhotoImage(file="lee.jpg") #imports image from file
label = Label(root, image=image) #creates a Label object containing the image
label.pack() #packs the Label into the Tk window
root.mainloop() #starts event loop
This is probably the simplest way to achieve the desired result.
If you're new to Python I would suggest a free tutorial rather than Stack Overflow, and if you're new to tKinter then http://effbot.org/tkinterbook is your friend.
you can use pillow module
from PIL import Image
img = Image.open(r'path/to/file.png')
img.show()
i hope this helps....

Tkinter GUI Not Opening in Pydev (Liclipse)

When I am trying to run my program based off a sample Tkinter GUI, nothing happens. I am still new to Pydev, but I find this rather unusual. I have a Main.py file containing the code, and I try to simply run the module without any success.
I simply copy/pasted from this reference,
# Main.py
import tkinter as tk;
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello World\n(click me)"
self.hi_there["command"] = self.say_hi
self.hi_there.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=root.destroy)
self.quit.pack(side="bottom")
def say_hi(self):
print("hi there, everyone!")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
The only result of running the module is an empty Liclipse console dedicated to Main.py.
I have also tried other examples from other sites with no luck. Also, I am currently on MacOS if it matters.
Are you sure you have everything properly (working directory, python path...) configured in Liclipse? I have just tried in a fresh install and, after configuring Liclipse to run the current project in Python 3.6 and after selecting the main project file as being this source code, it runs and shows a window with a button, as intended, and it also prints the text to console.
Also, it does not feel very "pythonic" to initialize a button that way. I would rather suggest like this:
# Main.py
import tkinter as tk;
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
def create_widgets(self):
mytext = "Hello World\n(click me)"
self.hi_there = tk.Button(self, text=mytext, command=self.say_hi)
self.hi_there.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red", command=root.destroy)
self.quit.pack(side="bottom")
def say_hi(self):
print("hi there, everyone!")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
The code looks a little more readable and works in the same way. When you start growing your interface, it will be many lines long and by reducing two lines at each button, you can make it a lot shorter. I have been coding a tkinter app with more that 1500 lines of code and at that point I promised myself that I would try to learn how to keep it more organized and short ;)

EXE file for python scripts

i am using python 2.7 and py2exe to try and make an exe file for my script. but it is not going so well.. my file works perfectly until I add the py2exe commands what am I doin wrong here? I need to know how to write the setup function and call it so that python knows to create and EXE file not just a compiled .py. Also this is attempted using a windows operating system.
from time import strftime
import os.path
# setup.py
import py2exe
setup(console=["LogFile.py"])
def main():
getTime()
def getTime():
time = strftime("%Y-%m-%d %I:%M:%S")
printTime(time)
def printTime(time):
savePath = "C:\Users\Nicholas\Documents"
logFile = "LogInLog.txt"
files = open(os.path.join(savePath, logFile), "a+")
openPosition = files.tell()
files.write("A LogIn occured.")
files.write(time)
files.seek(openPosition)
print(files.read())
files.close()
main()
It doesn't work that way
First, remove the setup line from your script. The setup script is a different script. Your script, fixed:
from time import strftime
import os.path
def main():
getTime()
def getTime():
time = strftime("%Y-%m-%d %I:%M:%S")
printTime(time)
def printTime(time):
savePath = r"C:\Users\Nicholas\Documents"
logFile = "LogInLog.txt"
files = open(os.path.join(savePath, logFile), "a+")
openPosition = files.tell()
files.write("A LogIn occured.")
files.write(time)
files.seek(openPosition)
print(files.read())
files.close()
Then create a file called setup.py
import py2exe
from distutils.core import setup
setup(console=["LogFile.py"])
Then type (in a command prompt, not from within python interpreter):
python setup.py py2exe
it creates the executable & aux files in dist subdir
After that go to dist
C:\DATA\jff\data\python\stackoverflow\dist>LogFile.exe
Traceback (most recent call last):
File "LogFile.py", line 25, in <module>
File "LogFile.py", line 6, in main
File "LogFile.py", line 10, in getTime
File "LogFile.py", line 15, in printTime
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Nicholas\\Documents\\LogInLog.txt'
crashing, normal I don't have your directories: it works!!
Look at this py2exe Tutorial.
Your mistakes are:
1. Missed from distutils.core import setup
2. Did not make a new file to use py2exe.
You need:
1. Remove import py2exeand setup(console=["LogFile.py"])
2. create new file "psetup.py", with code bellow:
from distutils.core import setup
import py2exe
setup(console=["your_code_name.py"])

Win32com Save PDF to XML with Acrobat Pro X > com_error "-2147467263, 'Not implemented'" [duplicate]

This question already has answers here:
"Not implemented" Exception when using pywin32 to control Adobe Acrobat
(2 answers)
Closed 6 years ago.
Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Windows XP SP3
Python 2.7 pywin32-218
Adobe Acrobat X 10.0.0
I want to use Python to automate Acrobat Pro to export a PDF to XML. I already tried it manually using the 'Save As' dialog box from the running program and now want to do it via a Python script. I have read many pages including parts of the Adobe SDK, SDK Forum, VB Forums and am having no luck.
I read Blish's problem here: "Not implemented" Exception when using pywin32 to control Adobe Acrobat
And this page: timgolden python/win32_how_do_i/generate-a-static-com-proxy.html
I am missing something. My code is:
import win32com.client
import win32com.client.makepy
win32com.client.makepy.GenerateFromTypeLibSpec('Acrobat')
adobe = win32com.client.DispatchEx('AcroExch.App')
avDoc = win32com.client.DispatchEx('AcroExch.AVDoc')
avDoc.Open('C:\Documents and Settings\PC\Desktop\a_PDF.pdf', 'C:\Documents and Settings\PC\Desktop')
pdDoc = avDoc.GetPDDoc()
jObject = pdDoc.GetJSObject()
jObject.SaveAs('C:\Documents and Settings\PC\Desktop\a_PDF.xml', "com.adobe.acrobat.xml-1-00")
The full error is:
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
jObject.SaveAs('C:\Documents and Settings\PC\Desktop\a_PDF.xml', "com.adobe.acrobat.xml-1-00")
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 511, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
com_error: (-2147467263, 'Not implemented', None, None)
I'm guessing it has to do with make.py but I don't understand how to implement it in my code.
I pulled this line from my code and got the same error when I ran it:
win32com.client.makepy.GenerateFromTypeLibSpec('Acrobat')
I then changed these two lines from 'DispatchEX' to 'Dispatch' and same error:
adobe = win32com.client.Dispatch('AcroExch.App')
avDoc = win32com.client.Dispatch('AcroExch.AVDoc')
When I run the Dispatches by themselves and then call them back I get:
>>> adobe = win32com.client.DispatchEx('AcroExch.App')
>>> adobe
<win32com.gen_py.Adobe Acrobat 10.0 Type Library.CAcroApp instance at 0x18787784>
>>> avDoc = win32com.client.Dispatch('AcroExch.AVDoc')
>>> avDoc
<win32com.gen_py.Adobe Acrobat 10.0 Type Library.CAcroAVDoc instance at 0x20365224>
Does this mean I should make only one call to Dispatch? I pulled:
adobe = win32com.client.Dispatch('AcroExch.App')
and got the same error.
This Adobe site says:
AVDoc
Product availability: Acrobat, Reader
Platform availability: Macintosh, Windows, UNIX
Syntax
typedef struct _t_AVDoc* AVDoc;
A view of a PDF document in a window. There is one AVDoc per displayed document. Unlike a PDDoc, an AVDoc has a window associated with it.
acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/API_References/Acrobat_API_Reference/AV_Layer/AVDoc.html#AVDocSaveParams
The PDDoc page says:
A PDDoc object represents a PDF document. There is a correspondence between a PDDoc and an ASFile. Also, every AVDoc has an associated PDDoc, although a PDDoc may not be associated with an AVDoc.
/9.1/Acrobat9_1_HTMLHelp/API_References/Acrobat_API_Reference/PD_Layer/PDDoc.html
I tried the following code and also got the same error:
import win32com.client
import win32com.client.makepy
pdDoc = win32com.client.Dispatch('AcroExch.PDDoc')
pdDoc.Open('C:\Documents and Settings\PC\Desktop\a_PDF.pdf')
jObject = pdDoc.GetJSObject()
jObject.SaveAs('C:\Documents and Settings\PC\Desktop\a_PDF.xml', "com.adobe.acrobat.xml-1-00")
Same error if I change:
pdDoc = win32com.client.Dispatch('AcroExch.PDDoc')
to
pdDoc = win32com.client.gencache.EnsureDispatch('AcroExch.PDDoc')
like here: win32com.client.Dispatch works but not win32com.client.gencache.EnsureDispatch
user2993272, you were almost there: just one more line and the code you have should have worked flawlessly.
I'm going to attempt to answer in the same spirit as your question and provide you as much details as I can.
This thread holds the key to the solution you are looking for: https://mail.python.org/pipermail/python-win32/2002-March/000260.html
I admit that the post is not the easiest to find (perhaps Google scores it low based on the age of the content?).
Specifically, applying this piece of advice will get things running for you: https://mail.python.org/pipermail/python-win32/2002-March/000265.html
For completeness, this piece of code should get the job done and not require you to manually patch dynamic.py (snippet should run pretty much out of the box):
# gets all files under ROOT_INPUT_PATH with FILE_EXTENSION and tries to extract text from them into ROOT_OUTPUT_PATH with same filename as the input file but with INPUT_FILE_EXTENSION replaced by OUTPUT_FILE_EXTENSION
from win32com.client import Dispatch
from win32com.client.dynamic import ERRORS_BAD_CONTEXT
import winerror
# try importing scandir and if found, use it as it's a few magnitudes of an order faster than stock os.walk
try:
from scandir import walk
except ImportError:
from os import walk
import fnmatch
import sys
import os
ROOT_INPUT_PATH = None
ROOT_OUTPUT_PATH = None
INPUT_FILE_EXTENSION = "*.pdf"
OUTPUT_FILE_EXTENSION = ".txt"
def acrobat_extract_text(f_path, f_path_out, f_basename, f_ext):
avDoc = Dispatch("AcroExch.AVDoc") # Connect to Adobe Acrobat
# Open the input file (as a pdf)
ret = avDoc.Open(f_path, f_path)
assert(ret) # FIXME: Documentation says "-1 if the file was opened successfully, 0 otherwise", but this is a bool in practise?
pdDoc = avDoc.GetPDDoc()
dst = os.path.join(f_path_out, ''.join((f_basename, f_ext)))
# Adobe documentation says "For that reason, you must rely on the documentation to know what functionality is available through the JSObject interface. For details, see the JavaScript for Acrobat API Reference"
jsObject = pdDoc.GetJSObject()
# Here you can save as many other types by using, for instance: "com.adobe.acrobat.xml"
jsObject.SaveAs(dst, "com.adobe.acrobat.accesstext")
pdDoc.Close()
avDoc.Close(True) # We want this to close Acrobat, as otherwise Acrobat is going to refuse processing any further files after a certain threshold of open files are reached (for example 50 PDFs)
del pdDoc
if __name__ == "__main__":
assert(5 == len(sys.argv)), sys.argv # <script name>, <script_file_input_path>, <script_file_input_extension>, <script_file_output_path>, <script_file_output_extension>
#$ python get.txt.from.multiple.pdf.py 'C:\input' '*.pdf' 'C:\output' '.txt'
ROOT_INPUT_PATH = sys.argv[1]
INPUT_FILE_EXTENSION = sys.argv[2]
ROOT_OUTPUT_PATH = sys.argv[3]
OUTPUT_FILE_EXTENSION = sys.argv[4]
# tuples are of schema (path_to_file, filename)
matching_files = ((os.path.join(_root, filename), os.path.splitext(filename)[0]) for _root, _dirs, _files in walk(ROOT_INPUT_PATH) for filename in fnmatch.filter(_files, INPUT_FILE_EXTENSION))
# Magic piece of code that should get everything working for you!
# patch ERRORS_BAD_CONTEXT as per https://mail.python.org/pipermail/python-win32/2002-March/000265.html
global ERRORS_BAD_CONTEXT
ERRORS_BAD_CONTEXT.append(winerror.E_NOTIMPL)
for filename_with_path, filename_without_extension in matching_files:
print "Processing '{}'".format(filename_without_extension)
acrobat_extract_text(filename_with_path, ROOT_OUTPUT_PATH, filename_without_extension, OUTPUT_FILE_EXTENSION)
I have tested this on WinPython x64 2.7.6.3, Acrobat X Pro

wxPython FileDialog crash in mac

I have the following code:
import wx
from sys import platform
wildcard = "CSV files|*.csv|"\
"XML files|*.xml|"\
"Microsoft Excel files|*.xlsx" if platform == "win32" else "CSV files|*.csv|"\
"XML files|*.xml|"
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = wx.Frame(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
dlg = wx.FileDialog(
frame_1, message="Choose a file",
defaultDir="",
defaultFile="",
wildcard=wildcard, #PROBLEM IS HERE THAT'S FOR SURE
style=wx.OPEN
)
dlg.ShowModal() #IT CRASHES HERE
dlg.Destroy()
app.MainLoop()
This FileDialog works perfect in Windows and Linux but crashes in Mac OS X. Is there anything I could change in order to get FileDialog working properly in Mac OS X?
Python 2.7.3, wxPython 2.8, Mac OS X 10.6
UPDATE: Updated to be a small sample.
UPDATE 2: Without "wildcard" parameter it works great but I need wildcard anyway.
Just found answer myself:
http://trac.wxwidgets.org/ticket/4489
It crashes in Mac when wildcard improperly formatted, after removing last "|" in wildcard everything work just fine.

Resources