Python app in autorun doesn't open file - python

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')

Related

Python: Changement of path when executing

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...

How to call python script in different directory using subprocess?

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.

Run Python Script From Script Directory/Current Directory

[Introduction]
Hi! I'm working on a python script to automate installation of UWP-Apps, it's been a long time i'm not touching Python; until this day. The script uses Depedencies inside the script directory, i've looking up on my older scripts and found this specific code.
os.chdir(os.path.dirname(sys.argv[0]))
[Problematic]
However, using the above code doesn't work on my current script but it's working fine on older scripts. When using above, it shows:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ''
Already looking up on Internet about this topic; but most of them was talking about running the script from outer/different directory that leads me to dead end.
Any helps is appreciated :)
The easiest answer is probably to change your working directory, then call the .py file from where it is:
cd path/to/python/file && python ../.py
Of course you might find it even easier to write a script that does it all for you, like so:
Save this as runPython.sh in the directory where you're running the python script from, is:
#!/bin/sh
cd path/to/python/file
python ../script.py
Make it executable (for yourself):
chmod +x ./runPython.sh
Then you can simply enter your directory and run it:
./runPython.sh
If you want to only make changes to the python script:
mydir = os.getcwd() # would be the folder where you're running the file
mydir_tmp = "path/to/python/file" # get the path
mydir_new = os.chdir(mydir_tmp) # change the current working directory
mydir = os.getcwd()
The reason you got an error was because sys.argv[0] is the name of the file itself, instead you can pass the directory as a string and use sys.argv[1] instead.
import os
from os.path import abspath, dirname
os.chdir(dirname(abspath(__file__)))
You can use dirname(abspath(__file__))) to get the parent directory of the python script and os.chdir into it to make the script run in the directory where it is located.

Pyinstaller: Executable file opened with built in function in python closes after 1 sec when i make .exe file with pyinstaller

I make program in python to open some executable file given by path. I use:
os.startfile(path)
to start program. When i run script.py in IDLE it works fine, but when i make .exe file with pyinstaller when i run it that program i want to open starts to open and closes almost immediately. I tried with different functions like subprocess.Popen(path) and it does the same thing, open and close program after 1 second. Can someone help me? Is there a problem in python functions or in pyinstaller or even windows 10?
The problem is that your code most likely just runs and then the window closes.
You can add import time to your imports and time.sleep(x) or something to keep the window open for x seconds after you run
Read all the way through before doing anything!
Ok so try this:
Put this in a python file called start.py:
import os
import subprocess
#py_command - whatever opens python in cmd
#path - must be full path of file you want to call
def StartPythonScript(path, py_command):
command = 'start cmd /k ' + py_command + " " + path
subprocess.run(command, shell=True)
Now, take the code from file you are calling from the exe, let's say its name is run.py, and put it in a different file, say code.py.
Make sure start.py is in the same folder as run.py
In run.py, put this:
import start
cmd = "py" #change this to whatever opens python in cmd
path = "code.py" #change to the full path of code.py
start.StartPythonScript(path, cmd)
So when you click on the exe, it opens run.py which tells start.py to open code.py, which contains your program.
You can actually merge start.py and run.py, but you can reuse start.py if they are seperate.
OR...
Add import os to your program that is called by the exe.
Add os.system("pause") to the end of your program.
I'm not sure if this will work on an infinitely running program...but try this first to save time.
More info:
How to stop Python closing immediately when executed in Microsoft Windows
Good luck!

No file creation with logging module in py2app mac application

I've got a python script that uses the logging module to create a log file. Using the following line:
logging.basicConfig(filename='debug.lg',filemode='w', level=logging.DEBUG)
This works great as a script. After compiling with py2app the log file is no longer created.
If I change the above line to,
logging.basicConfig(format = '%(levelname)s:%(message)s', level=logging.DEBUG)
and then force the console window open i get the expected logging printout. This tells me the logging module is working in my app.\
I anticipate this is some permission or virtual environment issue.
How do I make my log file be created (in the same directory that the app exists)
The mac app appears to run in a virtual environment. I can force the app to run with a console window open and print sys.argv[0] I see that I'm four folders deep in my .app file. This is where the log file is being created. I'm unable to navigate here in finder. If i set the absolute path of the log file four folders up (the location of the .app file) the log file stays after execution.

Categories