I am trying to make a desktop app on windows, with every files in a directory called: FINALS.
There are 2 python files (main.py and temp.py) used for logic, backend and these 2 files are using 2 other files .json to save data and use it (data.json and subjects.json)
To be more flexible, instead of copying the full path of the .json files in the python files, I used for exemple:
with open(f"{self.path}\\subjects.json") as subjects_file:
subjects = json.load(subjects_file)
with self.path beeing:
self.path = os.getcwd()
So everything is working fine since a execute code from the python file.
But I created a gui.py to get an interface with tkinter, using main.py and temp.py for the logic which are themselves using data.json and subjects.json for data management.
But when I execute the gui.py, I get quickly an error:
with open(f"{self.path}\\subjects.json") as subjects_file:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Program Files\\JetBrains\\PyCharm Community Edition 2021.3\\jbr\\bin\\subjects.json'
Apparently Pycharm is changing the path when executing, but only when the GUI is executing ?
Hope it was clear and you will be able to help me
EDIT: Apparently only PyCharm does that because I tried executing the GUI from VSCode and it worked...
Related
I have the following code to run a program located at
/Users/*/Downloads/Mood Script Static and another located a folder deeper at /Users/*/Downloads/Mood Script Static Edit/LowMood_Static. Now I am trying to invoke a subprocess controller that will run two python scripts, like this:
subprocess.call(['python3', 'SubjectSFbalance.py'])
print("\n")
time.sleep(0.5)
subprocess.call(['python3', 'LowMood_Static/LowMoodZScoring.py'])
However, when running the 2nd process, it correctly finds the .py script, but pandas cannot read the .csv files that are given in the LowMoodZScoring.py file, which is this:
Normalized_Subj = pd.read_csv('../SF_Output_Files/finished_sf_balance.csv')
giving the following error:
FileNotFoundError: [Errno 2] No such file or directory: '../SF_Output_Files/finished_sf_balance.csv'
However, when I run LowMoodZScoring.py without using the subprocess, I get no such error. What in subprocess is causing this error?
At first glance, since those CSV paths are relative, it looks like you need to add cwd="LowMood_Static" to the parameters of your subprocess call, so that it will run with that directory as the working directory.
To avoid this in a more comprehensive/future-proof way, it would be even better to have your LowMoodZScoring.py script load the CSV files relative to the directory of that script (i.e. os.path.dirname(__file__)), instead of relative to the current working directory.
I have recently made an app that does automatic assigment submissions using selenium. I would like to convert this .py file to a .exe so i can give it to others to use on thier computers.
This is the current directory of the project:
C:
canvas automation
chromedriver.exe
main.py
canvas_subjects.txt
In the main.py file, it uses canvas_subjects.txt file as below:
with open('c:/canvas automation/canvas_subjects.txt', 'r+') as subjects:
chrome_dir = 'C:/PythonProjects/Web Scraping/Selenium/chromedriver.exe'
driver = webdriver.Chrome(chrome_dir)
driver.minimize_window()
if subjects.read() != '':
# does the rest of the program here
When i try and convert main.py to .exe, running the .exe file produces the error:
Failed to execute main script
I'm guessing that when it runs the python script, it cannont find the following directory:
c:/canvas automation/canvas_subjects.txt
To convert this file to .exe, i have tried using pyinstaller:
C:\Users\user> pip install pyinstaller
C:\Canvas Automation> pyinstaller main.py
# also tried
C:\Canvas Automation> pyinstaller --onefile -w main.py
.exe file is created but outputs the same error.
I have tried auto-py-to-exe but it says that you need to incorporate the following code into your script so that the .exe file can find the directory but i do not understand how to use it:
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
You can't include a txt file in an exe like that. You have 2 solutions here:
Deliver your .txt file alongside the .exe like a part of the installation
Put the content of your text file inside a .py file as a string variable.
NB1: Are you sure you need an exe? could you not distribute it as a python soft, needing python to be executed?
NB2: Either way, you really should not use absolute paths like 'c:...' if you plan to distribute your soft
If you are having trouble including .txt files, try the following command to enable it in order:
CTRL+A
Backspace
CTRL+S
ALT+F4
If problems persist, please let me know.
I'm trying to write a script where it will move a directory (containing images to be processed) into another dedicated working directory (within the project folder) by using shutil.move().
However, my Python script keeps on failing to achieve this by throwing an [Errno 2] No such file or directory: '/Users/user/Desktop/Captured\\ Images' exception.
The target directory is being perfectly recognised so that's not the issue.
I'm currently using macOS to develop this script, and using standard BASH.
This is how I input the path of the source directory (by dragging the folder into the terminal): /Users/user/Desktop/Captured\ Images.
This is how Python interprets the source directory: /Users/user/Desktop/Captured\\ Images.
The script works perfectly when I modify the source path to: /Users/user/Desktop/Captured Images.
I've also tried using the Pathlib Module to prevent file separator issues, but that also didn't work.
I know for sure that what's causing the problem is the \ within the file path since the folder is named 'Captured Images' with a space between it, thus Captured\ Images.
Here's the following source code:
move_directory(input("Please Input The Directory Of The Captured Images You Would Like To Import: "))
def move_directory(source_directory):
try:
shutil.move(source_directory, os.path.dirname(os.path.dirname(__file__)) + '/Captured Images/Source Images')
except OSError as errorMessage:
print("Failed To Move Directory: {0}".format(errorMessage))
Update 1:
I've just tried to move the directories by using subprocess.run(["mv", ...]) and it worked, so now I see that it's not how the script is taking in the input, but a problem between the path input and shutil.move().
Why don't I get a json file written to disk in the current working directory (script location) when executing the following script? Shouldn't dump() do this?
def getShotFolders():
shotDict = {
"root" : shotExample,
"shot_subdirs" : []
}
for root, dirs, files in os.walk(shotExample, topdown=False):
if root != shotExample:
shotDict["shot_subdirs"].append(os.path.relpath(root,shotExample))
pprint(shotDict)
with open("shot_folderStructure.json", "w") as write_file:
json.dump(shotDict, write_file )
getShotFolders()
EDIT: Ok, I run my python files from vscode with right click 'execute python file in terminal' which outputs the C:/Python27/python.exe c:/Users/user/Desktop/test.py command.
If I run the script from pycharm with the same python set as the project interpreter the json files are created, but why?
EDIT2: ok for some reason when I execute the script the cwd is my home folder, shouldn't it be to the path of the python script. I know this can be fixed by os.chdir(os.path.dirname(__file__)) but it shouldn't be this way right?
Make sure you are opening your C:\Users\user\Desktop folder in VS Code in order to set the cwd to your desktop (if you open the file directly then it won't change your working directory).
I created an application that is running at windows startup, but every time it give me an Error:
[Errno 2] No such file or directory: 'user'
that error happen only at startup, if I open it normally (with doubleclick) it works good.
Note: I created the .exe with Pyinstaller and the file called 'user' is in the same directory of .exe (Program Files/App1/main.exe)
Maybe autorun works like a temp folder that can't recognize the content of Program Files directory?
Your program should never count on the current working directory being the same as the directory it's run from. If the user runs your program from the command line, or you put it in a batch file, or you launch it from autorun, or another program tries to run it… in all those cases, the working directory will be somewhere else.
sys.argv[0] gives you the path to your program. So:
import sys
import os
scriptdir = os.path.dirname(os.path.abspath(sys.argv[0]))
userpath = os.path.join(scriptdir, 'user.exe')