Pyinstaller create a data file at runtime - python

I created a .exe file with Pyinstaller. The program should create a data file with the results at runtime. It works in the Python interpreter mode when I execute python test.py but it doesn't work in the .exe mode. It simply doesn't create a file and responds with an error.
Which flags should I add to the command python -m PyInstaller --hidden-import=timeit --hidden-import=bisect -F test.py to make it work?
The exception with this setup is:
Error: [Errno 2] No such file or directory: "C:\Users\Admin\AppData\Local\Temp\..."
Where the aforementioned directory is temporary and I don't have access to it.
The piece of code which is supposed to write a file is:
def write_file(data, path, encoding='utf-8'):
'''Creates report files.'''
try:
if config.python_version == 2 and type(data) in (list, str):
f = io.open(path, 'wb')
else:
f = io.open(path, 'w', encoding=encoding, newline='')
if type(data) is list:
writer = csv.writer(f)
writer.writerows(data)
else:
f.write(data)
f.close()
console(u'Report file: ' + path)
except IOError as e:
console(e, level=Level.error)
I assume there should be a setting to point to the place where the file should be saved.
I've checked here https://pyinstaller.readthedocs.io/en/stable/spec-files.html#adding-files-to-the-bundle but without success. I couldn't use the listed flags properly, nothing seemed to work.
How can I specify the place where the file would be saved?

The issue isn't with pyinstaller, it's with however you're creating your file.
You may be using some environment variable when running your python script from the command line that isn't set when you run your Exe
I have created a simple example of a program that creates a data file in the directory from which it is called:
#myscript.py
f = open("Test.txt", "w")
print("Hello World!", file=f)
Then I generate the Exe with Pyinstaller:
pyinstaller -F myscript.py
Copy the exe anywhere and you can create Test.txt, if you have permissions in that folder.
Double click myscript.exe
Test.txt appears in the same folder as myscript.exe
Hello World!

Related

Compiled exe needs to be run as admin but uncompiled py file doesn't?

I recently compiled a python project I have been working on for some time to an exe, only to find you'd need to run it as an administrator for it to work, despite it not requiring any elevation while it was simply a .py file. It returns an internal error "cannot create temporary directory!" if you don't run it with elevation. I presume this has to do something with the program reading/writing to the users appdata/locallow folder (it stores some of it's files in there). Is there a simple fix to this? I'd much prefer it if the apps files could remain in one of the appdata folders whether it be local, locallow or roaming.
This can be reproduced by following these steps:
create a main.py file with the following code inside:
import os, json
LOG_DIR = os.path.expanduser('~\AppData\Locallow\AppName\logs')
LOG_PATH = os.path.expanduser('~\AppData\Locallow\AppName\logs\log.txt')
PREFS_DIR = os.path.expanduser('~\AppData\Locallow\AppName\prefs')
PREFS_PATH = os.path.expanduser('~\AppData\Locallow\AppName\prefs\prefs.json')
user_prefs = None
def log_init():
if os.path.isfile(LOG_PATH):
with open(LOG_PATH, 'a') as f:
f.close()
else:
if not os.path.isdir(LOG_DIR):
os.mkdir(LOG_DIR)
with open(LOG_PATH, 'w') as f:
f.close()
def prefs_init():
global user_prefs
if os.path.isfile(PREFS_PATH):
user_prefs = json.load(open(PREFS_PATH, 'r'))
else:
if not os.path.isdir(PREFS_DIR):
os.mkdir(PREFS_DIR)
with open(PREFS_PATH, 'w') as f:
f.write('{"welc_msg": "DirNav - The all in one file browser and terminal!", "file_color": {}}')
f.close()
user_prefs = json.load(open(PREFS_PATH, 'r'))
log_init()
prefs_init()
Make the following folder: C:/Users/YOUR_USER/AppData/Locallow/AppName
Running main.py will generate 'prefs' and 'logs' with respective files inside.
Delete 'prefs' and 'logs'
Compile main.py using this command: pyinstaller -F main.py
Running the new .exe that is in the 'dist' folder from cmd will result in an 'INTERNAL ERROR: cannot create temporary directory!' message.
Run the .exe again but this time run as an administrator and it will work perfectly fine
The main premise here is why does the executable need to be run as an admin yet the .py file doesn't? And how do I make it so the executable doesn't need to be run as an admin?

How to fix 'FileNotFoundError' in a pre-written file?

I am trying to set up GPT-2 encoding using the following tutorial:
https://medium.com/#ngwaifoong92/beginners-guide-to-retrain-gpt-2-117m-to-generate-custom-text-content-8bb5363d8b7f
I am trying to enter
python encode.py giselle.txt giselle.npz
in the command prompt but it keeps giving me a FileNotFoundError for an encoder.json file that is already in the path it tries to retrieve it from.
How may I go about fixing this?
I have tried editing the encode.py file to specify the exact path to the encoder.json file but it still gives FileNotFoundError
def get_encoder(model_name):
with open(os.path.join('models', model_name, 'encoder.json'), 'r') as f:
encoder = json.load(f)
with open(os.path.join('models', model_name, 'vocab.bpe'), 'r', encoding="utf-8") as f:
bpe_data = f.read()
I expected the giselle.txt to be encoded to the giselle.npz file but all that is sent in the command prompt is
File "C:\projectgiselle\gpt-2-finetuning\src\encoder.py", line 109, in get_encoder
with open(os.path.join('models', model_name, 'encoder.json'), 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'models\\117M\\encoder.json'
I had this same error!
The tutorial is geared towards Windows users and has you copy train.py and encode.py into the /src/ directory for 'simplicity', so that you don't have to modify the PYTHONPATH. But moving these might violate the code's expectations of where certain scripts are. The solution is simply to move the expect files (encoder.json) correspondingly.
I was able to successfully continue the tutorial by copying and pasting the entire /model/ folder into /src/, so that /src/model/. Then you can run encode.py from /src/ as it instructs.

Vsc is giving an error but the python idle doesent?

I wrote a program, and when I run it in Visual Studio Code it gives an error but not when I run it in the Python IDLE. I have set up the environment variable but it still doesn't work. So can u please tell me how to fix this
This also has happened when I import a file and all sorts of places where I want to use a different file
This is my compiler.py file
fileName = "file.txt"
file = open("file.txt", "r+")
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
for loop in range(file_len(fileName) + 1) :
print(loop)
and this is my file.txt
hallo
When I run this in Visual Studio Code it gives this error
PS C:\Users\Harry Kruger\Documents\code> & "C:/Program Files (x86)/Python37-32/python.exe" "c:/Users/Harry Kruger/Documents/code/quicks/compiler.py"
hallo
Traceback (most recent call last):
File "c:/Users/Harry Kruger/Documents/code/quicks/compiler.py", line 4, in <module>
file = open("file.txt", "r+")
FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'
And when i run ir in python IDLE it works and the output is this
0
1
I guess that you run python IDLE in the directory "c:/Users/Harry Kruger/Documents/code/quicks. Therefore your code will pass because in this directory is (probably?) also the file.txt.
However in VS Code you seem to run python in the directory C:\Users\Harry Kruger\Documents\code where the file.txt is not present and therefore your code fails.
To fix this and run your code in VS Code you have two options:
In VS Code powershell navigate to the directory that contains the file.txt. In your case you should be able to do it by entering cd "c:/Users/Harry Kruger/Documents/code/quicks" and then call your code.
You can modify your code to use the absolute path of the file. Then you can invoke it from any directory. To do so you have to modify the with open() statement. Replace it with:
from os import path
with open(path.join(path.abspath(path.dirname(__file__)), 'file.txt'), 'r+') as f:
this snipet will look for the absoulte path of the file and open it.

file line writing closes off script

I'm looking to make a file that when you enter a directory, it creates a folder inside that directory. I'm using a batch file to create the folder, so I'm making it when you enter the directory, it will write that directory to the batch file, then run it. However I'm having some errors. Here's my code
directory = str(input())
text = 'cd ' + directory
lines = open('new.bat', 'r').readlines()
lines[2] = text
out = open('new.bat', 'w')
out.writelines(lines)
out.close()
call('new.bat')
out.close() exits my python script before it can have a chance to call 'new.bat', however if I move the out.close() to after it calls new.bat, it gives me an error that the file is currently being used. How do I fix this?

Opening a file in pwdir's folder in Python through Applescript

Opening a file available in present working directory's temp folder in python
I tried
pwdir=os.getcwd()
tempdir=pwdir+"/temp/test.txt"
f=open(tempdir,'r+')
When I print the path of tempdir, it is showing up correctly and also the contents of file are also read.
When I try to combine this operation from an Applescript, which calls this python script. I get an error like this
f=open(pwdir1,'r+')
IOError: [Errno 2] No such file or directory: '//temp/test.txt'" number 1
EDIT:
I am using Shell script from Applescript to call this pythonscript
do shell script "/Users/mymac/Documents/'Microsoft User Data'/test.py"
EDIT:
Python Code:
tempdir = os.path.join(os.getcwd(),'temp','htmlinput.html')
print tempdir
with open(tempdir) as f:
html=f.read()
Python output from terminal:(works perfectly fine)
/Users/mymac/Documents/Microsoft User Data/Outlook Script Menu Items/temp/htmlinput.html
I am also able to see the file contents.
Applescript Code:
do shell script "/Users/mymac/Documents/'Microsoft User Data'/'Outlook Script Menu Items'/new.py"
Applescript Error:
error "Microsoft Outlook got an error: Traceback (most recent call last):
File \"/Users/mymac/Documents/Microsoft User Data/Outlook Script Menu Items/new.py\", line 12, in <module>
with open(tempdir) as f:
IOError: [Errno 2] No such file or directory: '/temp/htmlinput.html'" number 1
I don't know Applescript -- or OS X in general. It looks like the script is being run from the root folder, and os.getcwd() returns '/'. The directory of the script itself is sys.path[0] or the dirname of the current module -- dirname(__file__) -- if it's a single script instead of a package. Try one of the following
import os, sys
tempdir = os.path.join(sys.path[0], 'temp', 'temp.txt')
or
import os
tempdir = os.path.join(os.path.dirname(__file__), 'temp', 'temp.txt')
The double slash is your problem. The right way to join file and path names in Python is with os.path.join. Try:
tempdir = os.path.join(os.getcwd(), 'temp', 'test.txt')
Also, you should probably be doing:
with open(tempdir) as f:
which will make sure tempdir gets closed even if you have an error.
Edit:
We need to see what tempdir is when the script is invoked by the AppleScript, not when it is invoked from the terminal. If you do
tempdir = os.path.join(os.getcwd(),'temp','htmlinput.html')
with open('/Users/mymac/Documents/temp.txt', 'w') as fwrite:
fwrite.write(tempdir)
What exactly ends up in the file /Users/mymac/Documents/temp.txt?

Categories

Resources