I have compiled my python program with cx_Freeze with the lines
import sys
print(sys.argv[0])
to get the name of the extension file that runs my application.
I want to be able to double click on a file named Foo.bas and then my compiled executable starts and it can open the file and read its contents. So I want to get the extension path and file name and read its contents like this
with open(file, "r") as f:
data = f.read()
# do things with contents
where file would be the extension path and name
So how would I do that?
sys.argv[0] gives you the first entry of the command used to run your script, which is the script name itself. If you double-click on a file whose extension is associated with your script or frozen application, the name of this file becomes the second argument of the command, which is available through sys.argv[1]. See for example sys.argv[1] meaning in script.
So try with the following script:
import os
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
print('Trying with', filename)
if os.path.isfile(filename):
with open(filename, 'r') as f:
data = f.read()
# do things with contents
else:
print('No arguments provided.')
input('Press Enter to end')
This works both as unfrozen script and as executable frozen with cx_Freeze. On Windows you can drag and drop your Foo.bas file onto the icon of your script or executable, or right-click on Foo.bas, chose Open with and select your script or executable as application.
Related
I want my python file to run if Windows is booted up every single time, so I used this simple code:
Background.py (This creates a .bat file which will run my desired .py file on every windows startup)
import getpass
import os
USER_NAME = getpass.getuser()
def add_to_startup():
bat_path = r'C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup' % USER_NAME
with open(bat_path + '\\' + "open.bat", "w+") as bat_file:
bat_file.write(r'C:\Users\intel\AppData\Local\Programs\Python\Python38\python.exe C:\Users\intel\Desktop\Python programs\testing.py %*')
add_to_startup()
And this is the .py file which I want to run every time:
with open(r"C:\Users\intel\Desktop\hello.txt", "w+") as test_file:
test_file.write(r'start')
But it's not working even if my computer is on :(
Edit 1:
I checked The startup folder also and the open.bat file is successfully created and existing...
(You can even check in the image)
enter code here
I have two files, one bell.mp3 one main.py file, that plays back bell.mp3 via subprocess.
If I do:
pyinstaller main.py
the Dist file ends up correctly, and everything works fine, The program runs in a directory.
This is the code for my file which i call pyinst_tester.py
it creates a text file, and plays a bell.mp3 file
#
from con import * # this is just a configuration file that has g='play' in it.
import subprocess
f=open(r'/home/godzilla/Desktop/Pyinstaller testing/testfile1','w')
f.write('This has worked')
f.close()
file='/home/godzilla/Desktop/Pyinstaller testing/data/bell.mp3'
if 'play' == g:
subprocess.call(['/usr/bin/cvlc',file])
a single file is created, but if I delete the bell.mp3 file it doesn't work. In a single file isn't the bell.mp3 zipped inside the main.exe ? therefore, redundant as a separate file ?
What Is the point having a single file exe, if you need an adjacent file with all the mp3s inside?
Pyinstaller has many features and if you want to include non python files (for example mp3 files) you have to do so explicitly with the --add-binary switch.
In one file mode the executable will be unpacked into a temporary directory prior to execution of the python code.
So how to write your code to access these data files.
You might want to look at the pyinstaller documention at following sections:
https://pyinstaller.readthedocs.io/en/stable/runtime-information.html#run-time-information
https://pyinstaller.readthedocs.io/en/stable/runtime-information.html#using-sys-executable-and-sys-argv-0
I personally place all my files in a separate directory. e.g. data.
If you place the file bell.mp3 in the directory data, then you had to call pyinstaller with the option --add-binary data:data
in the one file mode the executable is extracted into a temporary directory
whose path you get get from the variable sys._MEIPASS
Your data directory will bi in the sub directory data of sys._MEIPASS
In my example I create a function, that will be able to locate the data files in normal python mode and in pyinstaller one file or one directory mode.
Just try it out it should be self explaining
simple example:
minitst.py
import os, sys
import time
is_frozen = getattr(sys, "frozen", False)
MYDIR = os.path.realpath(os.path.dirname(__file__))
def data_fname(fname):
if is_frozen:
return os.path.join(sys._MEIPASS, "data", fname)
else:
return os.path.join(MYDIR, "data", fname)
def main():
print("This application is %s frozen" %
("" if is_frozen else "not"))
print("executable =", sys.executable,
"File =", __file__,
"mydir =", MYDIR)
if is_frozen:
print("MEIPASS", sys._MEIPASS)
fname = data_fname("tst.txt")
print("will open", fname)
with open(fname) as fin:
print(fin.read())
time.sleep(5) # this shall allow to view the console e.g. on windows if clicking on the executable.
if __name__ == "__main__":
main()
now create a directory data and place a file "tst.txt"
data/tst.txt
Hello world
Now call
pyinstaller -F minitst.py --add-binary data:data -c
and call dist/minitst from a console.
The output should look like:
This application is frozen
executable = /home/gelonida/so/pyinst/dist/minitst File = minitst.py mydir = /home/gelonida/so/pyinst
MEIPASS /tmp/_MEIKGqah9
will open /tmp/_MEIKGqah9/data/tst.txt
Hello
Now concerning your code.
I compacted the code to determine the datadir a little, but it is the same logic as in the upper example
import os, sys
from con import * # this is just a configuration file that has g='play' in it.
import subprocess
basedir = getattr(sys, "_MEIPASS", os.path.realpath(os.path.dirname(__file__)))
f=open('testfile1','w')
f.write('This has worked')
f.close()
file=os.path.join(basedir, 'data/bell.mp3')
if 'play' == g:
subprocess.call(['/usr/bin/cvlc',file])
I am trying to run a Python Script through Excel VBA
I have tried the following code, but nothing happened:
Here is the VBA code:
RetVal = Shell("C:\Program Files\Python37\python.exe C:\Users\kailung\Desktop\kai\VBA\june_Longchen\test\VBA.py")
My python script is just renaming files within a folder (I've tested it in Python IDLE, it is fine):
import os, sys
dir_path = os.path.dirname(os.path.realpath(__file__))
# Open a file
dirs = os.listdir(dir_path)
i=1
# This would print all the files and directories
for file in dirs:
if file!='VBA.xlsm' and file!='VBA.py' and file!='~$VBA.xlsm':
print(file) #print all the files
i=str(i) #change to string for file name
i=i + '.xls' #add extension
os.rename(file,i) #rename the file
size=len(i)
i=i[0:size-4] #remove the extension
i=int(i) #change back to numerical
i=i+1 #new numerical name
Convert your .py file to .exe file using pyinstaller and run the .exe program directly from VBA code.
How to use pyinstaller?
def Function222(inF):
inF = open("C:\\Users\\Dell\\Desktop\\FF1\\txttt.txt")
outputF=open("output.txt", "w")
lines=inF.readlines()
for line in lines:
outputF.write('\n')
outputF.write(line*4)
inF.close()
outputF.close()
I need to create a new file called outputF and it should show up in the same folder that the inF is in, the problem is that it doesn't appear in the folder and I searched for the file on my computer but didn't find it
Get the Path:
import os
path= os.path.abspath("C:/example/cwd/mydir/myfile.txt")
open new file in path and write to it
Because the current working directory isn't the directory of the input file. Use os.getcwd() to get the current working directory, if it doesnt't match the directory of the input file, then you need to change your working directory first:
import os
def Function222(inF):
inF = open("C:\\Users\\Dell\\Desktop\\FF1\\txttt.txt")
#change the working directory
os.chdir("C:\\Users\\Dell\\Desktop\\FF1")
outputF=open("output.txt", "w")
lines=inF.readlines()
for line in lines:
outputF.write('\n')
outputF.write(line*4)
inF.close()
outputF.close()
Which folder location do I store text files on my computer for python to access? I'm trying to open a file called word.txt with the command fin = open('words.txt').
You need to use the full path to the file.
with open('/path/to/words.txt', 'r') as handle:
print handle.read()
Otherwise, it will be using your current directory.
import os
# Print your current directory
print os.path.abspath(os.curdir)