Reputation: 25
I want to make a python application with a sound being executed when pressing a button and I also want users to download it from somewhere. But, I have to add an mp3 file to play the sound. The mp3 file must be in the same directory as the .py file. But when the user downloads it, the directory changes according to his PC. So, how will I make it so that the mp3 file is in the same directory as the .py file to recognize it and play it? Is there any way to completely add the mp3 file in the .py file without it being seperated? If yes how? Thanks!
Upvotes: 1
Views: 676
Reputation: 43563
To address this problem (including data in a Python script) I wrote py-include.
The core of that program is basically this:
with open(path, "rb") as img:
data = img.read()
data = base64.b85encode(data).decode("ascii")
It encodes the binary file contents using base85 encoding and converts it to text.
An example:
python src/scripts/public/py-include.py /usr/local/lib/firefox/browser/chrome/icons/default/default16.png
# /usr/local/lib/firefox/browser/chrome/icons/default/default16.png
data = base64.b85decode(
'iBL{Q4GJ0x0000DNk~Le0000G0000G2nGNE03Y-JVE_OEnMp)JRCoc5j04PNM-<0@Gjs9$KCit'
'&ZQHhO8(|qWsu|UG8`qAjU~S`j_PclH^ww_oBu9U-B_*}v9!PrmKXLkh&6|$A5hphyGE>Hndf;'
'CJ<dw-g%3ITC^4IG0?jnl8x}@bsS$o)pf20+F+%s`UhT~7jnVaa%-GMP`>e#RDmTz`D5Z@$t3P'
'K+MVh4l|;`z_2$?txr0Oa=R%PDkclJTkpg9Dvt>Vxk;`vjwNR-KrgvS#MMwhNfC&*xw?sHB|-z'
'P|!xcQSJ2))xX7q6JJpMWzASXwOP%=RKQicNplbo=tVdRJ{CViX*GQ8IYtM18BQY(+W<Y9Y7wK'
'n1X>ke!9gz=UmS&m)(k+SfOKw$WJeUZ=m6z30NTF1nsKXnMnv#LkI-Y28Ii)>L1AWt50XOoyE8'
'<^1*#qL$?S07%B?74(WLVUOZmhG4Nwp0c;BC93(vO)Wg)gtqFrH*}#$NIcl4WP;Wyg4J89Zb*K'
'#BY0Iayf&&r2YQ|TlSh7iAWCOm=k#j!zeoTQ)u+c)(M}jVt6*LXzMtk6a>3m~HM1#{5b)EHj!;'
'<yGM7E1<H<5as6SjMnNve$W0@Oeosb!#<{?y#)4yu8>F!X!iG}J<NEzD=k-wdrT6Wkik9(|K-('
'+dGmfrZEruNgtb{!I#CUGch42B)n%FwC@3eguI{ItI@rZNW&=4pIsVhHg7CtHL{}r(QhC1CYo+'
'X?*3RPqL$>9SZ|3bQGbwzXl|&e{8{troC_obn!cHl#2iq0KnSpO#@EFZ%f!dFk5U9r22$mgwl>'
'EQuMnay;>0+Wj^(Da?-%6$Etq{_(RZzNzetN?17>jpwQx>op~qO?@ns}u$~3T>H$)`AslTIpBD'
'fC002ovPDHLkV1f'
)
Include the output from this script in your Python file, and data
will contain the (binary) contents of the icon as bytes
, which you can then e.g. save to a temporary file.
Note that the data will become ≈1.35 times as big because of the encoding.
py-include
has an option to compress files before encoding, but since an MP3 file is already heavily compressed that doesn't yield a size reduction in this case.
Upvotes: 2
Reputation: 2013
A possible solution to package your application + dependecies is to create an executable from them.
I personally use pyInstaller and py2exe, but these answers cover the topic more in detail.
How can I make a Python script standalone executable to run without ANY dependency?
Create a single executable from a Python project
Upvotes: 1