Python 2.7에서이 코드를 실행하면 다음 오류가 발생합니다.
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\pyutilib.subprocess-3.5.4\setup.py", line 30, in <module>
long_description = read('README.txt'),
File "C:\Python26\Lib\site-packages\pyutilib.subprocess-3.5.4\setup.py", line 19, in read
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
NameError: global name '__file__' is not defined
코드는 다음과 같습니다.
import os
from setuptools import setup
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(name="pyutilib.subprocess",
version='3.5.4',
maintainer='William E. Hart',
maintainer_email='wehart@sandia.gov',
url = 'https://software.sandia.gov/svn/public/pyutilib/pyutilib.subprocess',
license = 'BSD',
platforms = ["any"],
description = 'PyUtilib utilites for managing subprocesses.',
long_description = read('README.txt'),
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: Microsoft :: Windows',
'Operating System :: Unix',
'Programming Language :: Python',
'Programming Language :: Unix Shell',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Software Development :: Libraries :: Python Modules'],
packages=['pyutilib', 'pyutilib.subprocess', 'pyutilib.subprocess.tests'],
keywords=['utility'],
namespace_packages=['pyutilib'],
install_requires=['pyutilib.common', 'pyutilib.services']
)
답변
이 오류는 os.path.join(os.path.dirname(__file__))
파이썬 대화 형 쉘 에이 줄을 추가 할 때 발생합니다 .
Python Shell
현재 파일 경로를 감지하지 않으며이 줄을 추가 한 사용자 __file__
와 관련 filepath
이 있습니다.
따라서이 줄 os.path.join(os.path.dirname(__file__))
을 file.py
. 그런 다음 실행 python file.py
하면 파일 경로가 필요하기 때문에 작동합니다.
답변
PyInstaller와 Py2exe에서 동일한 문제가 발생하여 cx-freeze의 FAQ에 대한 해결책을 찾았습니다.
콘솔에서 또는 응용 프로그램으로 스크립트를 사용할 때 아래의 기능은 “실제 파일 경로”가 아닌 “실행 경로”를 제공합니다.
print(os.getcwd())
print(sys.argv[0])
print(os.path.dirname(os.path.realpath('__file__')))
출처:
http://cx-freeze.readthedocs.org/en/latest/faq.html
이전 라인 (초기 질문) :
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
코드 줄을 다음 스 니펫으로 대체하십시오.
def find_data_file(filename):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = os.path.dirname(__file__)
return os.path.join(datadir, filename)
위의 코드를 사용하면 OS 경로에 애플리케이션을 추가 할 수 있으며, 앱이 데이터 / 구성 파일을 찾을 수 없다는 문제없이 어디서나 실행할 수 있습니다.
Python으로 테스트했습니다.
- 3.3.4
- 2.7.13
답변
다음과 같이 코드를 변경하십시오! 그것은 나를 위해 작동합니다. `
os.path.dirname(os.path.abspath("__file__"))
답변
__file__
예상대로 작동하지 않는 경우가 발생했습니다 . 그러나 다음은 지금까지 나를 실패하지 않았습니다.
import inspect
src_file_path = inspect.getfile(lambda: None)
이것은 C의 파이썬 아날로그에 가장 가까운 것입니다. __FILE__
입니다.
Python의 동작은 __file__
C의 동작과 많이 다릅니다.__FILE__
. C 버전은 소스 파일의 원래 경로를 제공합니다. 이는 오류를 기록하고 어떤 소스 파일에 버그가 있는지 아는 데 유용합니다.
Python __file__
은 현재 실행중인 파일의 이름 만 제공하므로 로그 출력에서 그다지 유용하지 않을 수 있습니다.
답변
답변
파일을 문자열로 처리하여 해결했습니다. 즉, "__file__"
대신 (따옴표와 함께!)__file__
이것은 나를 위해 잘 작동합니다.
wk_dir = os.path.dirname(os.path.realpath('__file__'))
답변
당신이 찾고있는 모든 것이 현재 작업 디렉토리를 얻는 것이라면 코드의 다른 곳에서 작업 디렉토리를 변경하지 않는 os.getcwd()
한 동일한 것을 제공합니다 os.path.dirname(__file__)
. os.getcwd()
대화 형 모드에서도 작동합니다.
그래서
os.path.join(os.path.dirname(__file__))
이된다
os.path.join(os.getcwd())
