I'd like to open/display an excel file that I'm saving as part of python processing within the python script.
The save portion of the code works fine (ie, it saves successfully, and I'm open and view from a Nautilus window), but attempting to open programmatically throws errors no matter how I attempt it.
I've been using the Popen method within the subprocess package:
from subprocess import Popen
Popen('./temp/testtest.xlsx')
Gives:
PermissionError: [Errno 13] Permission denied: './temp/testtest.xlsx'
I subsequently tried changing file permissions:
import os
from subprocess import Popen
os.chmod('./temp/testtest.xlsx',0o777)
Popen('./temp/testtest.xlsx')
Which gave:
Out[127]: <subprocess.Popen at 0x7faeb22a4b00>invalid file (bad magic number): Exec format error
And against better judgement tried running as shell:
from subprocess import Popen
Popen('./temp/testtest.xlsx', shell=True)
Which gave:
invalid file (bad magic number): Exec format error
Out[129]: <subprocess.Popen at 0x7faeb22a46a0>
I also tried it with the file saved in a different directory with similar errors. If it matters, I'm using the openpyxl module to create and save the excel file, but I have the same issues even if it's an excel file I created manually.
The argument to Popen() needs to be a shell command to open the file. If you're using LibreOffice, the program is localc; if you're using OpenOffice it's oocalc.
from subprocess import Popen
import os
f = os.path.join('temp', filename)
Popen(['localc', f])
You have Many options here. You could install libreoffice, this is an open source office suite and is fairly decent you should be able to open that file directly with ooffice —-calc “filename”. If you really want to stay with python You could save the data to a .csv file, and pythons anaconda distribution has pandas library and you could read the .csv into a data frame fairly easily. import pandas as pd Then
pd.read_csv(“File_name.csv”) returns to you a dataframe, but remember to import os and os.chdir(r“/path/to/data”).
From that point pandas lets you easily access the data for plotting or manipulation.
Here is all the functionality of a data frame and see if it meets your fancy.
Python Pandas DataFrame
Currently working with the example script found on IBM Watson's GitHub:
Link: https://github.com/watson-developer-cloud/python-sdk/blob/master/examples/text_to_speech_v1.py
When I run the script, it works perfectly creating the WAV file. However, when I try to play it back within the script, it simply runs and never plays. I tried using PyAudio, Os, Subprocess, and other third party libraries to play the file, however, nothing worked. Is there something I would have to do to the file first before attempting to play it in the script? I'm assuming it has something to do with it being written in binary, which is what the script calls for, but I'm still too new at programming to understand how to solve the problem.
I'll attach my full script below with placeholders for personal info. Thanks!
# coding=utf-8
from os.path import join, dirname
from watson_developer_cloud import TextToSpeechV1
from watson_developer_cloud.websocket import SynthesizeCallback
import subprocess
service = TextToSpeechV1(url='EXAMPLE URL TO API', iam_apikey='EXAMPLE API KEY')
with open(join(dirname(__file__), '..EXAMPLE PATH../resources/output2.wav'),'wb') as audio_file:
response = service.synthesize("What's the weather?", accept='audio/wav', voice="en-US_MichaelVoice").get_result()
audio_file.write(response.content)
def audio_call():
audio_file_path = "..EXAMPLE PATH../resources/output2.wav"
return subprocess.call(["afplay", audio_file_path])
audio_call()
[SOLVED]: Apparently there was a problem with my file directory playing WAV files. By changing the file acceptance to "accept = 'audio/wav'" it worked fine.
I am trying to make a python program that creates and writes in a txt file.
the program works, but I want it to cross the "hidden" thing in the txt file's properties, so that the txt can't be seen without using the python program I made. I have no clues how to do that, please understand I am a beginner in python.
I'm not 100% sure but I don't think you can do this in Python. I'd suggest finding a simple Visual Basic script and running it from your Python file.
Assuming you mean the file-properties, where you can set a file as "hidden". Like in Windows as seen in screenshot below:
Use operating-system's command-line from Python
For example in Windows command-line attrib +h Secret_File.txt to hide a file in CMD.
import subprocess
subprocess.run(["attrib", "+h", "Secret_File.txt"])
See also:
How to execute a program or call a system command?
Directly call OS functions (Windows)
import ctypes
path = "my_hidden_file.txt"
ctypes.windll.kernel32.SetFileAttributesW(path, 2)
See also:
Hide Folders/ File with Python
Rename the file (Linux)
import os
filename = "my_hidden_file.txt"
os.rename(filename, '.'+filename) # the prefix dot means hidden in Linux
See also:
How to rename a file using Python
I am using the cx_Freeze script located in the Python36/Scripts folder on a regular basis to convert python files into executables and it works fine. However it seems to still not being able to convert numpy so I am trying to make it work by adding an option into the main.py which is used by the cx_Freeze script described above. This main.py is located in the site-packages/cx_Freeze folder.
Thomas K. provided a solution here: Creating cx_Freeze exe with Numpy for Python
by adding this line to the options:
options = {"build_exe": {"packages": ["numpy.lib.format"]}}
Is it possible to add this line to the main.py in the options section? If so how would I do that?
Your help is much appreciated.
If I understand correctly what you like to do, you could try to add the following two lines to the file site-packages/cx_Freeze/freezer.py
## -127,6 +127,8 ## class Freezer(object):
self.includes = list(includes)
self.excludes = list(excludes)
self.packages = list(packages)
+ if 'numpy.lib.format' not in self.packages:
+ self.packages.append('numpy.lib.format')
self.namespacePackages = list(namespacePackages)
self.replacePaths = list(replacePaths)
self.compress = compress
I thought I heard that py2exe was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?
Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.
The way to do this using py2exe is to use the bundle_files option in your setup.py file. For a single file you will want to set bundle_files to 1, compressed to True, and set the zipfile option to None. That way it creates one compressed file for easy distribution.
Here is a more complete description of the bundle_file option quoted directly from the py2exe site*
Using "bundle_files" and "zipfile"
An easier (and better) way to create
single-file executables is to set
bundle_files to 1 or 2, and to set
zipfile to None. This approach does
not require extracting files to a
temporary location, which provides
much faster program startup.
Valid values for bundle_files are:
3 (default) don't bundle
2 bundle everything but the Python interpreter
1 bundle everything, including the Python interpreter
If zipfile is set to None, the files will be bundle
within the executable instead of library.zip.
Here is a sample setup.py:
from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1, 'compressed': True}},
windows = [{'script': "single.py"}],
zipfile = None,
)
PyInstaller will create a single .exe file with no dependencies; use the --onefile option. It does this by packing all the needed shared libs into the executable, and unpacking them before it runs, just as you describe (EDIT: py2exe also has this feature, see minty's answer)
I use the version of PyInstaller from svn, since the latest release (1.3) is somewhat outdated. It's been working really well for an app which depends on PyQt, PyQwt, numpy, scipy and a few more.
As the other poster mention, py2exe, will generate an executable + some libraries to load. You can also have some data to add to your program.
Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.
I have used InnoSetup with delight for several years and for commercial programs, so I heartily recommend it.
I've been able to create a single exe file with all resources embeded into the exe.
I'm building on windows. so that will explain some of the os.system calls i'm using.
First I tried converting all my images into bitmats and then all my data files into text strings.
but this caused the final exe to be very very large.
After googleing for a week i figured out how to alter py2exe script to meet my needs.
here is the patch link on sourceforge i submitted, please post comments so we can get it included in
the next distribution.
http://sourceforge.net/tracker/index.php?func=detail&aid=3334760&group_id=15583&atid=315583
this explanes all the changes made, i've simply added a new option to the setup line.
here is my setup.py.
i'll try to comment it as best I can.
Please know that my setup.py is complex do to the fact that i'm access the images by filename.
so I must store a list to keep track of them.
this is from a want-to-b screen saver I was trying to make.
I use exec to generate my setup at run time, its easyer to cut and paste like that.
exec "setup(console=[{'script': 'launcher.py', 'icon_resources': [(0, 'ICON.ico')],\
'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\
options={'py2exe': py2exe_options},\
zipfile = None )" % (bitmap_string[:-1])
breakdown
script = py script i want to turn to an exe
icon_resources = the icon for the exe
file_resources = files I want to embed into the exe
other_resources = a string to embed into the exe, in this case a file list.
options = py2exe options for creating everything into one exe file
bitmap_strings = a list of files to include
Please note that file_resources is not a valid option untill you edit your py2exe.py file as described in the link above.
first time i've tried to post code on this site, if I get it wrong don't flame me.
from distutils.core import setup
import py2exe ##UnusedImport
import os
#delete the old build drive
os.system("rmdir /s /q dist")
#setup my option for single file output
py2exe_options = dict( ascii=True, # Exclude encodings
excludes=['_ssl', # Exclude _ssl
'pyreadline', 'difflib', 'doctest', 'locale',
'optparse', 'pickle', 'calendar', 'pbd', 'unittest', 'inspect'], # Exclude standard library
dll_excludes=['msvcr71.dll', 'w9xpopen.exe',
'API-MS-Win-Core-LocalRegistry-L1-1-0.dll',
'API-MS-Win-Core-ProcessThreads-L1-1-0.dll',
'API-MS-Win-Security-Base-L1-1-0.dll',
'KERNELBASE.dll',
'POWRPROF.dll',
],
#compressed=None, # Compress library.zip
bundle_files = 1,
optimize = 2
)
#storage for the images
bitmap_string = ''
resource_string = ''
index = 0
print "compile image list"
for image_name in os.listdir('images/'):
if image_name.endswith('.jpg'):
bitmap_string += "( " + str(index+1) + "," + "'" + 'images/' + image_name + "'),"
resource_string += image_name + " "
index += 1
print "Starting build\n"
exec "setup(console=[{'script': 'launcher.py', 'icon_resources': [(0, 'ICON.ico')],\
'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\
options={'py2exe': py2exe_options},\
zipfile = None )" % (bitmap_string[:-1])
print "Removing Trash"
os.system("rmdir /s /q build")
os.system("del /q *.pyc")
print "Build Complete"
ok, thats it for the setup.py
now the magic needed access the images.
I developed this app without py2exe in mind then added it later.
so you'll see access for both situations. if the image folder can't be found
it tries to pull the images from the exe resources. the code will explain it.
this is part of my sprite class and it uses a directx. but you can use any api you want or just access the raw data.
doesn't matter.
def init(self):
frame = self.env.frame
use_resource_builtin = True
if os.path.isdir(SPRITES_FOLDER):
use_resource_builtin = False
else:
image_list = LoadResource(0, u'INDEX', 1).split(' ')
for (model, file) in SPRITES.items():
texture = POINTER(IDirect3DTexture9)()
if use_resource_builtin:
data = LoadResource(0, win32con.RT_RCDATA, image_list.index(file)+1) #windll.kernel32.FindResourceW(hmod,typersc,idrsc)
d3dxdll.D3DXCreateTextureFromFileInMemory(frame.device, #Pointer to an IDirect3DDevice9 interface
data, #Pointer to the file in memory
len(data), #Size of the file in memory
byref(texture)) #ppTexture
else:
d3dxdll.D3DXCreateTextureFromFileA(frame.device, ##UndefinedVariable
SPRITES_FOLDER + file,
byref(texture))
self.model_sprites[model] = texture
#else:
# raise Exception("'sprites' folder is not present!")
Any questions fell free to ask.
You should create an installer, as mentioned before. Even though it is also possible to let py2exe bundle everything into a single executable, by setting bundle_files option to 1 and the zipfile keyword argument to None, I don't recommend this for PyGTK applications.
That's because of GTK+ tries to load its data files (locals, themes, etc.) from the directory it was loaded from. So you have to make sure that the directory of your executable contains also the libraries used by GTK+ and the directories lib, share and etc from your installation of GTK+. Otherwise you will get problems running your application on a machine where GTK+ is not installed system-wide.
For more details read my guide to py2exe for PyGTK applications. It also explains how to bundle everything, but GTK+.
I'm told bbfreeze will create a single file .EXE, and is newer than py2exe.
I recently used py2exe to create an executable for post-review for sending reviews to ReviewBoard.
This was the setup.py I used
from distutils.core import setup
import py2exe
setup(console=['post-review'])
It created a directory containing the exe file and the libraries needed. I don't think it is possible to use py2exe to get just a single .exe file. If you need that you will need to first use py2exe and then use some form of installer to make the final executable.
One thing to take care of is that any egg files you use in your application need to be unzipped, otherwise py2exe can't include them. This is covered in the py2exe docs.
try
c_x freeze
it can create a good standalone