开发者

howoto fix working directory is always home? (python)

开发者 https://www.devze.com 2023-01-05 06:41 出处:网络
This is my first question. My python script opens and reads from a present text file using the following simple funct:

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 e开发者_如何学Gorror 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消