running a python script as administrator - python

i'm writing an installer using py2exe which needs to run in admin to have permission to perform various file operations. i've modified some sample code from the user_access_controls directory that comes with py2exe to create the setup file. creating/running the generated exe works fine when i run it on my own computer. however, when i try to run the exe on a computer that doesn't have python installed, i get an error saying that the import modules (shutil and os in this case) do not exist. it was my impression that py2exe automatically wraps all the file dependencies into the exe but i guess that this is not the case. py2exe does generate a zip file called library that contains all the python modules but apparently they are not used by the generated exe. basically my question is how do i get the imports to be included in the exe generated by py2exe. perhaps modification need to be made to my setup.py file - the code for this is as follows:
from distutils.core import setup
import py2exe
# The targets to build
# create a target that says nothing about UAC - On Python 2.6+, this
# should be identical to "asInvoker" below. However, for 2.5 and
# earlier it will force the app into compatibility mode (as no
# manifest will exist at all in the target.)
t1 = dict(script="findpath.py",
dest_base="findpath",
uac_info="requireAdministrator")
console = [t1]
# hack to make windows copies of them all too, but
# with '_w' on the tail of the executable.
windows = [{'script': "findpath.py",
'uac_info': "requireAdministrator",
},]
setup(
version = "0.5.0",
description = "py2exe user-access-control",
name = "py2exe samples",
# targets to build
windows = windows,
console = console,
)

Try to set options={'py2exe': {'bundle_files': 1}}, and zipfile = None in setup section. Python will make single .exe file without dependencies. Example:
from distutils.core import setup
import py2exe
setup(
console=['watt.py'],
options={'py2exe': {'bundle_files': 1}},
zipfile = None
)

I rewrite your setup script for you. This will work
from distutils.core import setup
import py2exe
# The targets to build
# create a target that says nothing about UAC - On Python 2.6+, this
# should be identical to "asInvoker" below. However, for 2.5 and
# earlier it will force the app into compatibility mode (as no
# manifest will exist at all in the target.)
t1 = dict(script="findpath.py",
dest_base="findpath",
uac_info="requireAdministrator")
console = [t1]
# hack to make windows copies of them all too, but
# with '_w' on the tail of the executable.
windows = [{'script': "findpath.py",
'uac_info': "requireAdministrator",
},]
setup(
version = "0.5.0",
description = "py2exe user-access-control",
name = "py2exe samples",
# targets to build
windows = windows,
console = console,
#the options is what you fail to include it will instruct py2exe to include these modules explicitly
options={"py2exe":
{"includes": ["sip","os","shutil"]}
}
)

Related

How to use cx_Freeze to make an executable python program

I downloaded cx_Freeze because I'm trying to make a .exe file to share with my platoon and I've been reading through the docs as well as scrolling through cx_Freeze tutorial. After following both of those I still don't know why this isn't working for me. I'm on Python 3.6.2 and I have the path directly setup to the command line.
I tried to launch with setup.py and Julian date 2.py on the desktop and I tried adding them to same folder, but no matter what I try I get back this error when I type python setup.py build, python: can't open file 'setup.py': [Error2] no such file or directory or file exsists. Below is my setup.py code.
from cx_Freeze import setup, Executable
setup(name = "Julian date 2" ,
version = "0.1" ,
description = "" ,
executables = [Executable("Julian date 2.py")])
Another issue I ran into was trying to type cxfreeze Julian date 2.py --target-dir dist I get the error 'cxfreeze' is not recognized as an internal or external command, operable program or batch file.
When you type python setup.py build, you are supposed to be in the directory with setup.py and not anywhere else. So use the command cd to get there.
cx_freeze is not in your path variable so cxfreeze Julian date 2.py --target-dir dist will not work and you have to instead add it to your path (somehow) [not recommended]
Hope this helped.
P.S.
executables = [Executable("Julian date 2.py")]) takes base too. If you want a console application:
executables = [Executable("Julian date 2.py",base='None')])
Gui for windows:
executables = [Executable("Julian date 2.py",base='Win32GUI')])
And you forgot your exe options in setup(). I recommend adapting the setup.py script on cx_freeze doxs:
import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]}
# GUI applications require a different base on Windows (the default is for a
# console application).
base = "None"
setup( name = "name",
version = "0.1",
description = " ",
options = {"build_exe": build_exe_options},
executables = [Executable("file.py", base=base)])
I solved the first issue, my file was named 'setup.py' and not just 'setup' as it's supposed to be...The name must be setup, the extension .py
Know it's DUMB, after hours, that was the problem...

Py2exe compiles properly but the built application doesn't work

I am using Python 2.7 to build my application. Within it, I used few packages which are numpy, scipy, csv, sys, xlwt, time, wxpython and operator.
All the above packages are in 64-bit, and I am using python 2.7(64-bit version) in Aptana Studio 3(64-bit version) in Windows 7 Professional (64-bit version).
At last, I'd like to compile my project to an application using following code, the file name is py2exeTest.py:
from distutils.core import setup
import numpy # numpy is imported to deal with missing .dll file
import py2exe
setup(console=["Graphical_Interface.py"])
Then in cmd, I switched to the directory of the project and used following line to compile it:
python py2exeTest.py py2exe
Everything goes well, it generates an application under dist directory, and the application name is Graphical_Interface.exe.
I double clicked it, but there is a cmd window appears, and a python output windows flashes, then both of them disappeared. I tried to run the application as an administrator, the same outcome I've had.
May I know how to work this out?
Thanks!
EDIT:
I've managed to catch the error information that flashes on the screen. The error info I had is:
Traceback (most recent call last):
File "Graphical_Interface.py", line 397, in <module>
File "Graphical_Interface.py", line 136, in __init__
File "wx\_core.pyc", line 3369, in ConvertToBitmap
wx._core.PyAssertionError: C++ assertion "image.Ok()" failed at ..\..\src\msw\bitmap.cpp(802) in wxBitmap::CreateFromImage(): invalid image
I used one PNG image in the project, the code is like follows:
self.workflow = wx.Image("Work Flow.png", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
wx.StaticBitmap(self.panel_settings, -1, self.workflow, (330,270), (self.workflow.GetWidth(), self.workflow.GetHeight()))
I tried to comment the above chunk out from the project, and the application works properly. However, I need the image to show up in the application.
May I know how to deal with it?
Thanks.
Hiding console window of Python GUI app with py2exe
When compiling graphical applications you can not create them as a console application because reasons (honestly can't explain the specifics out of my head), but try this:
from distutils.core import setup
import numpy
import py2exe
import wxpython
setup(window=['Graphical_Interface.py'],
options={"py2exe" { 'boundle_files' : 1}})
Also consider changing to:
http://cx-freeze.sourceforge.net/
It works with Python3 and supports multiple platforms.
A cx_freeze script would look something like:
import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]}
# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
base = "Win32GUI"
includefiles = ['/folder/image.png']
setup( name = "GUIprog",
version = "0.1",
description = "My GUI application!",
options = {"build_exe": build_exe_options, 'include_files' : includefiles},
executables = [Executable("Graphical_Interface.py", base=base)])
No worries, I've got the solution.
It turns out that the image is in the project folder rather than in the dist folder. So I have two solutions:
Copy the image into dist folder
Include the full path of the image in the code.
Thanks for your help.

Using cx_Freeze to Make First Program Into exe File

I made my first program (a gui calculator) in python using tkinter and am trying to use cx_freeze to turn it into an exe file. I'm really confused in how it works thought. I used cxfreeze quickstart in the scripts section of python33 to make my setup file. The program is named Calculator
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need
# fine tuning.
buildOptions = dict(packages = [], excludes = [])
executables = [
Executable('Calculator.py', 'Win32GUI')
]
setup(name='Calculator',
version = '1.0',
description = '',
options = dict(build_exe = buildOptions),
executables = executables)
When I got to the console and type python setup.py build I get the error:
cx_Freeze.freezer.ConfigError: no initscript named Win32GUI
can anyone recommend a tutorial for using cx_Freeze or any other programs to make python code as exe format?
I suggest you try PyInstaller.
To convert a script to an exe file, you'd have to type something like this in a command prompt:
/path/to/python/pythonX.Y pyinstaller.py --onefile /path/to/your/script.py
Simple as that.

Py2app keyflag error CFLAGS

What I'm trying to do is compile a program I've written in Python 2.7, using pygame, into a standalone app for Mac computers. I'm working on a PC running Windows 8 with no access to a mac, so tweaking the process has been difficult.
When I run the setup file from the command prompt, I get the "text flood" (similar to what py2exe gave me when it worked to compile the windows version) and the program appears to work. It creates build and dist folders, but the dist folder has no contents. When looking at the command prompt output, the last two lines are
BASE_CFLAGS = cfg['CFLAGS']
Key Error: 'CFLAGS'
This seems to happen when py2app is trying to create the application bundle.
Here is the setup.py file I've gotten to thus far:
"""
Script for building the example.
Usage:
python setup.py py2app
"""
from setuptools import setup
NAME = 'PetCute Slide Puzzle Test'
VERSION = '0'
plist = dict(
CFBundleIconFile=NAME,
CFBundleName=NAME,
CFBundleShortVersionString=VERSION,
CFBundleGetInfoString=' '.join([NAME, VERSION]),
CFBundleExecutable=NAME,
CFBundleIdentifier='Py2App and PyGam test',
)
setup(
data_files=['Dog1.jpg', 'Dog2.jpg', 'Dog3.jpg', 'Dog4.jpg', 'Dog5.jp', 'Dog6.jpg', 'Dog7.jpg', 'Dog8.jpg', 'Dog9.jpg', 'Dog10.jpg', 'Dog11.jpg', 'Dog12.jpg', 'Dog13.jpg', 'Dog14.jpg', 'Dog15.jpg', 'Dog16.jpg', 'AYearWithoutRain.ttf'],
app=[
dict(script="PetCute_slidepuzzle.py", plist=plist),
],
setup_requires=["py2app"],
)
The data_files lists out the pictures and text file that need to be bundled with the code. I got to this by adapting the alien.py example. Please let me know if any more info is needed!
It probably had an error during compilation. I suggest you make sure you have Numpy installed, its needed for py2app to compile Pygame programs.

Best of both worlds: python packaging for a game

I am currently trying to package a game made with python and pygame and I am running into some issues.
I am using py2exe to package and have looked up some question on here about it but I couldn't find a great solution. I want to end up with a folder, containing an exe, that I can compress and put online. Running the setup.py works fine except it puts all the dependencies into library.zip. This means that the program, when run, does not work.
I found that someone else was running into this issue and they ended using the "skip archive = true" option to solve it. And while, yes, that does work for me too I was hoping there was a method that would still let the program be run without trouble but wouldn't clutter the folder with countless files.
To be very precise the issue I'm running into with the library.zip is:
ImportError: MemoryLoadLibrary failed loading pygame\mixer.pyd
Which, if I understand it properly, means that the program can not reach/find the mixer module of Pygame.
Here is the setup script I am currently using (and that isn't working):
from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
data_files = [('resources', ['resources/step.wav',
'resources/wind2.wav',
'resources/The Steppes.ogg',
'resources/warrior3-nosword-notassle.png',
'resources/warrior3-sword.png',
'resources/warrior2-blood1.png',
'resources/warrior2-blood2.png',
'resources/warrior2-blood3.png',
'resources/warrior2-blood4.png',
'resources/warrior3-up.png',
'resources/warrior3-kneel.png',
'resources/warrior3-kneel-nosword.png',
'resources/warrior2-blood2-kneel.png',
'resources/warrior2-blood3-kneel.png',
'resources/warrior2-blood4-kneel.png',
'resources/warrior3-death.png',
'resources/warrior3-offarm.png',
'resources/menu1.png',
'resources/plains3-top-nomount.png',
'resources/mountains.png',
'resources/plains5-bottom.png',
'resources/plains3-bottom.png',
'resources/cloud1.png',
'resources/warrior2-sword.png',
'resources/warrior2-hand.png',
'resources/blue-tassle1.png',
'resources/blue-tassle2.png',
'resources/blue-tassle3.png',
'resources/blue-tassle4.png'])]
setup(options = {'py2exe': {"bundle_files": 1}},
data_files = data_files,
console = [{'script': "steppes2.0.py"}],
zipfile = None
)
This code in your setup.py should do the trick of producing a single executable (you will still have to distribute msvc dlls separately)
from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1}},
console = [{'script': "myscript.py"}],
zipfile = None,
)

Categories