파이썬에서 현재 실행중인 파일의 경로를 얻으려면 어떻게해야합니까?
이것은 초보자 질문처럼 보이지만 그렇지 않습니다. 일부 공통 접근 방식은 모든 경우에 작동하지 않습니다.
sys.argv [0]
이것은을 사용하는 것을 의미 path = os.path.abspath(os.path.dirname(sys.argv[0]))
하지만 다른 디렉토리의 다른 Python 스크립트에서 실행하는 경우 작동하지 않으며 실제로 발생할 수 있습니다.
__파일__
이것은을 사용하는 것을 의미 path = os.path.abspath(os.path.dirname(__file__))
하지만 이것이 작동하지 않는다는 것을 알았습니다.
py2exe
이없는__file__
속성을하지만,이 해결 방법은- 속성
execute()
이없는 IDLE에서 실행할 때__file__
- 내가 얻는 OS X 10.6
NameError: global name '__file__' is not defined
불완전한 답변이 포함 된 관련 질문 :
- Python-실행중인 파일 경로 찾기
- 현재 파일의 경로는 프로그램 실행 방법에 따라 다릅니다.
- 파이썬에서 실행중인 스크립트의 경로를 아는 방법?
- 디렉토리를 Python 스크립트의 디렉토리로 변경
위의 모든 유스 케이스에서 작동 하는 일반적인 솔루션을 찾고 있습니다.
최신 정보
테스트 케이스의 결과는 다음과 같습니다.
파이썬 a.py의 출력 (Windows)
a.py: __file__= a.py
a.py: os.getcwd()= C:\zzz
b.py: sys.argv[0]= a.py
b.py: __file__= a.py
b.py: os.getcwd()= C:\zzz
a.py
#! /usr/bin/env python
import os, sys
print "a.py: sys.argv[0]=", sys.argv[0]
print "a.py: __file__=", __file__
print "a.py: os.getcwd()=", os.getcwd()
print
execfile("subdir/b.py")
하위 디렉토리 /b.py
#! /usr/bin/env python
import os, sys
print "b.py: sys.argv[0]=", sys.argv[0]
print "b.py: __file__=", __file__
print "b.py: os.getcwd()=", os.getcwd()
print
나무
C:.
| a.py
\---subdir
b.py
실행중인 기본 스크립트의 위치를 직접 결정할 수 없습니다. 결국, 때로는 스크립트가 파일에서 전혀 나오지 않았습니다. 예를 들어, 대화식 인터프리터 또는 메모리에만 저장된 동적으로 생성 된 코드에서 가져올 수 있습니다.
그러나 모듈은 항상 파일에서로드되므로 모듈의 위치를 안정적으로 결정할 수 있습니다. 다음 코드를 사용하여 모듈을 작성하고 기본 스크립트와 동일한 디렉토리에 넣으면 기본 스크립트가 모듈을 가져 와서 해당 모듈을 찾을 수 있습니다.
some_path / module_locator.py :
def we_are_frozen():
# All of the modules are built-in to the interpreter, e.g., by py2exe
return hasattr(sys, "frozen")
def module_path():
encoding = sys.getfilesystemencoding()
if we_are_frozen():
return os.path.dirname(unicode(sys.executable, encoding))
return os.path.dirname(unicode(__file__, encoding))
some_path / main.py :
import module_locator
my_path = module_locator.module_path()
If you have several main scripts in different directories, you may need more than one copy of module_locator.
Of course, if your main script is loaded by some other tool that doesn't let you import modules that are co-located with your script, then you're out of luck. In cases like that, the information you're after simply doesn't exist anywhere in your program. Your best bet would be to file a bug with the authors of the tool.
First, you need to import from inspect
and os
from inspect import getsourcefile
from os.path import abspath
Next, wherever you want to find the source file from you just use
abspath(getsourcefile(lambda:0))
I was running into a similar problem, and I think this might solve the problem:
def module_path(local_function):
''' returns the module path without the use of __file__. Requires a function defined
locally in the module.
from http://stackoverflow.com/questions/729583/getting-file-path-of-imported-module'''
return os.path.abspath(inspect.getsourcefile(local_function))
It works for regular scripts and in idle. All I can say is try it out for others!
My typical usage:
from toolbox import module_path
def main():
pass # Do stuff
global __modpath__
__modpath__ = module_path(main)
Now I use __modpath__ instead of __file__.
this solution is robust even in executables
import inspect, os.path
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
The short answer is that there is no guaranteed way to get the information you want, however there are heuristics that work almost always in practice. You might look at How do I find the location of the executable in C?. It discusses the problem from a C point of view, but the proposed solutions are easily transcribed into Python.
See my answer to the question Importing modules from parent folder for related information, including why my answer doesn't use the unreliable __file__
variable. This simple solution should be cross-compatible with different operating systems as the modules os
and inspect
come as part of Python.
First, you need to import parts of the inspect and os modules.
from inspect import getsourcefile
from os.path import abspath
Next, use the following line anywhere else it's needed in your Python code:
abspath(getsourcefile(lambda:0))
How it works:
From the built-in module os
(description below), the abspath
tool is imported.
OS routines for Mac, NT, or Posix depending on what system we're on.
Then getsourcefile
(description below) is imported from the built-in module inspect
.
Get useful information from live Python objects.
abspath(path)
returns the absolute/full version of a file pathgetsourcefile(lambda:0)
somehow gets the internal source file of the lambda function object, so returns'<pyshell#nn>'
in the Python shell or returns the file path of the Python code currently being executed.
Using abspath
on the result of getsourcefile(lambda:0)
should make sure that the file path generated is the full file path of the Python file.
This explained solution was originally based on code from the answer at How do I get the path of the current executed file in Python?.
You have simply called:
path = os.path.abspath(os.path.dirname(sys.argv[0]))
instead of:
path = os.path.dirname(os.path.abspath(sys.argv[0]))
abspath()
gives you the absolute path of sys.argv[0]
(the filename your code is in) and dirname()
returns the directory path without the filename.
This should do the trick in a cross-platform way (so long as you're not using the interpreter or something):
import os, sys
non_symbolic=os.path.realpath(sys.argv[0])
program_filepath=os.path.join(sys.path[0], os.path.basename(non_symbolic))
sys.path[0]
is the directory that your calling script is in (the first place it looks for modules to be used by that script). We can take the name of the file itself off the end of sys.argv[0]
(which is what I did with os.path.basename
). os.path.join
just sticks them together in a cross-platform way. os.path.realpath
just makes sure if we get any symbolic links with different names than the script itself that we still get the real name of the script.
I don't have a Mac; so, I haven't tested this on one. Please let me know if it works, as it seems it should. I tested this in Linux (Xubuntu) with Python 3.4. Note that many solutions for this problem don't work on Macs (since I've heard that __file__
is not present on Macs).
Note that if your script is a symbolic link, it will give you the path of the file it links to (and not the path of the symbolic link).
You can use Path
from the pathlib
module:
from pathlib import Path
# ...
Path(__file__)
You can use call to parent
to go further in the path:
Path(__file__).parent
If the code is coming from a file, you can get its full name
sys._getframe().f_code.co_filename
You can also retrieve the function name as f_code.co_name
Simply add the following:
from sys import *
path_to_current_file = sys.argv[0]
print(path_to_current_file)
Or:
from sys import *
print(sys.argv[0])
My solution is:
import os
print(os.path.join(os.getcwd(), __file__))
import os
current_file_path=os.path.dirname(os.path.realpath('__file__'))
'Programing' 카테고리의 다른 글
String.Empty가 상수가 아닌 이유는 무엇입니까? (0) | 2020.05.19 |
---|---|
PHP로 PDF를 작성하는 가장 좋은 방법 (0) | 2020.05.19 |
ValueError : 둘 이상의 요소가있는 배열의 실제 값이 모호합니다. (0) | 2020.05.19 |
.NET에서 언제 SecureString이 필요합니까? (0) | 2020.05.19 |
.NET에서 언제 SecureString이 필요합니까? (0) | 2020.05.19 |