howoto fix working directory is always home? (python) - python

This is my first question.
My python script opens and reads from a present text file using the following simple funct:
open("config.ini", "r")
As this is a relative path it is supposed to work because config.ini is placed in the same directory like the script is when it is launched, that should be the current working dir.
In fact this works perfectly on all of my 3 linux boxes, but I have one user who demands support because he gets an error while opening config.ini. The error raises because
os.path.exists("config.ini")
returns false even if the file is there!
Trying to fix this problem we found out that the only way to make it work is to place config.ini in his home directory despite the supposed working directory is another.
Also, if my script tries to create a file in the present working directory, the file is always created in his home dir instead, and so I think that for some reason his working dir is always home!
How can I troubleshoot this problem? Maybe I could introduce absolute paths, but I am afraid that os.getcwd() would return the homedir instead of the correct one.
Should I maybe suggest this user to fix his machine in some way?
Sorry for this long question but english is not my first language and I am a beginner in coding, so have some difficulties to explain.
Thank you very much in advance! =)

Could it be that the user is executing your script from his home directory?
I.e. suppose the script is in:
/home/user/test/foo/foo.py
But the user calls it thus:
/home/user> python test/foo/foo.py
In this case, the "current directory" the script sees is /home/user.
What you can do is find out the directory the script itself resides in by calling this function:
import os
def script_dir():
return os.path.dirname(os.path.realpath(__file__))
It will always return the directory in which the script lives, not the current directory which may be different. You can then store your configuration file there safely.

Along the same lines as Eli Bendersky's suggestion, you might want to try:
os.path.exists(os.path.join(sys.path[0],"config.ini"))
since sys.path[0] should always be the directory in which the script resides.

Related

Way to make the directory universal (relative?) across different computers?

I am a high school student building a video game for a project, and you'll have to excuse me, I am very new to python/coding in general.
I assumed this would be a relatively easy thing to figure out or find online but I haven't had any luck. Obviously with a video game there are assets and files that need to be used. How can I set the directory to something that will work if run on another computer. More details below:
Right now I have it set to os.chdir(r'C:\Users\User\Desktop\VideoGame'), and obviously if run on another computer the path would be different. How can I set it so it find that "VideoGame" file and then sets that as the directory.
Obviously I need a directory so python can find all the files I need. But let's say i take my folder with my code and all my assets on it and put it on a USB stick, then give it to my teacher, how can I be sure that the python he is running can find and use the files in that folder.
After you clarified, what I understood is that you want to load all your game assets in a removable drive. I am assuming you will be having the assets folder in the directory where the main.py file will be present.
So my approach to the problem is to first obtain the current working directory of the main.py file and then add assets\ to it and then check if that directory actually exists or not. If yes, then carry on with the operation, else display an error message.
My solution:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
dir_path = os.path.join(dir_path, r"assets")
if(os.path.exists(dir_path)):
# block of code
print()
else:
print("assets not found!\ncheck your directory")
If I am again missing out something, fell free to comment.

Python: iNotify_Simple getting files from other directories

I'm using inotify_simple to get notifications from a directory of directories. I'm accessing a directory that has multiple sub-directories, looping through those sub-directories and wanting to use inotify within each directory. My goal for this program is to be notified anytime anything happens (in particular, a creation of a file) in one of the sub-directories.
My file structure:
-mainDir
-subDir1
-file1
-file2
-subDir2
-file3
-file4
...etc.
I'm looping through the directories in mainDir, and setting that path as the path for inotify to search in:
for directory in os.listdir(self.path):
new_path = os.path.join(self.path, directory)
new_curr = self.inotify.new_curr_file_notification(new_path)
New path values are exactly what I expect:
.../mainDir/subDir1
.../mainDir/subDir2
When passing in new_path into my function (which is the path to give inotify), I'm expecting inotify to only look in that directory. However, I'm getting notifications that files in other directories are causing the notification.
path for inotify .../mainDir/subDir1
Event(wd=1, mask=256, cookie=0, name='someFileInSubDir2')
flags.CREATE
Does anyone know why this is happening? And, if anyone has any suggestions to make this process easier/better, I'm all ears! Thanks!
I'm the author of inotify_simple, and since it doesn't have a method called new_curr_file_notification, I'm guessing that's that's something you wrote. Without seeing that method, or some more code that demonstrates how you're using the library exactly, I unfortunately can't give you any advice, as there's not enough information to see how you're using inotify_simple.
If you post a complete example, I will probably be able to tell what's going wrong.
Feel free to post a bug report on the project't github if it looks like there might be a bug.

White space in batch file and shelve saving in a different directory

I am having problems with Project Multiclipboard from Chapter 8 of the book: Automate the Boring Stuff and using Python 3.
The first issue is that, suppose my program mcb.pyw is saved in:
C:\Users\myName\folder name
where the last folder has a space in the name, my batch file:
#pyw.exe C:\Users\myName\folder name\mcb.pyw %*
doesn't seem to work properly from the command line. I can now type in
mcb save keyword
into the command line without getting an error, but it's not doing anything. After testing by changing the directory to a folder whose path has no space in it, I've concluded that the problem is because of the space, but I am unsure of how I might go about fixing this.
The second issue is that when the batch file is working, the module shelve seems to be saving the data in the wrong folder. Specifically, I noticed that if I were to run mcb.pyw from the command line, shelve would save the data in C:\Users\myName, which is also the default directory when you open the command windod, instead of the folder C:\Users\myName\folderName, where mcb.pyw and mcb.bat are saved.
I have gotten around this by including the lines:
import os
os.chdir('C:\\Users\\myName\\folderName')
However, is there any other way to solve this issue? Why is shelve saving in C:\Users\myName instead of the folder where everything is already saved?
I apologise if I have made any ettiquette or formatting problems. If you let me know what I did wrong I will do my best to fix it as soon as I can, thank you!
Files are always saved in the current working directory unless they are specified with path names, so you do have to change your working directory if the default one is not what you want.
You can avoid hard-coding the path name and always change your working directory where the script is located with:
import os
import sys
os.chdir(os.path.dirname(sys.argv[0]))

Geany and other IDE not writing to file

I'm using Geany as my editor and when I first started using it, writing to files worked fine but somehow it randomly stopped working. The code executes without any errors but the file isn't created / is empty if already created and I've no idea why.
Simple code as below doesn't work:
filename = 'dogs'
with open(filename, 'w') as f:
f.write('tester')
with open(filename, 'r') as f:
contents = f.read()
print(contents)
The output I get from the 'read' method looks correct on the console output (it just prints 'tester'), but no file is created / edited in my directory.
Geany also has a weirdly complex debugger (if anyone has any helpful guides on how to use it please let me know) so I can't debug properly. I've tried all that I know including using an absolute file path, running in admin mode. The issue is also present when I try to use Pygal to render_to_file(), which is the project I'm working on so right now I can't go any further because anything that requires writing doesn't work. FYI it reads fine.... It's like Geany doesn't have admin rights or something?
EDIT: I've run this code on a python shell (without a .py file) and it worked fine, creating the file as desired. I then ran it using CMD with the .py file and it didn't work. Also ran using Pycharm, it doesn't work when I run it normal but it works when I run it in debug mode? It doesn't seem to be a Geany specific issue, but I am so confused!
Because the code works in the shell I strongly suspect the file is being created somewhere but you are looking in the wrong place.
I know you mentioned absolute paths but I just want to reiterate that you are not currently using an absolute path. An absolute path must start with a '/' (linux/mac) or something like: 'C:/' (windows).
Here are 2 things to try:
1)
Change the name 'dogs' to something really obscure and then do a global search on your whole hard disk for that name. You'll probably find it.
2) Get python to tell you where the file is like this:
import os
filename = 'dogs'
with open(filename, 'w') as f:
f.write('tester')
print(os.path.realpath(f.name))
Got the solution - the files were being created the whole time every time I ran my code, however my antivirus software Comodo contained them within a hidden folder in my drive which couldn't be found by a normal search.
I'm not sure if this a common problem with AV software or just Comodo, can't find anything on the net about it but there you go. I removed these files and the programs from its radar and it now works perfectly.
Although one mystery is how the python shell bypassed that problem. That threw me off thinking it was AV.

Subprocess Call in Python 3

Hey guys I have a pretty simple code.
subprocess.call(dirIFLO+'IFLO.exe')
Where dirIFLO is just a folder above the current working directory
This code is suppose to run IFLO.exe while my code waits. The program does start but somehow it does not manage to get the files they were suppose to in the same directory it is. If I manually open it I get it working just fine.
I have managed to make it work by accessing the subdirectory and calling the program instead of opening the subroutine straight from the working directory.
w = os.getcwd()
os.chdir(dirIFLO[:-2])
subprocess.call('IFLO.exe')
os.chdir(w)

Categories