私はSphinxでカスタムPythonコードを実行しており、は呼び出し元モジュールへのパスを取得する必要があります。私はHow to use inspect to get the caller's info from callee in Python?あたりとしてinspect.stack()
からファイル名を取得することができますSphinx conf.pyで実行されるPython関数から呼び出し側モジュールのパスを取得する信頼できる方法はありますか?
が、どうやら私は、Pythonのコンテキストでこのファイル名を解釈する必要があります。(私はこの場所からの相対ファイル名を解釈する必要があります。基本的にこれは、呼び出し側の__file__
オブジェクトです)起動ディレクトリ。 (時にはinspect.stack()[k][1]
は絶対パスですが、時にはそれがconf.py
のような相対パスであり、inspect.stack()
関数はPythonの起動ディレクトリに相対的であることをunutbu claims in a commentしかし、これを文書化していないようです。)
スフィンクスは、いくつかの意図せず悪のことを行いますこのコメントのように:
# This file is execfile()d with the current directory set to its
# containing dir.
のでos.path.abspath(filename)
は動作しません、と
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('extensions'))
のでsys.path[0]
はcorrupです私のコードがそれに到達するまでに時間がかかりました。
sys.path
が変更されている場合、Pythonでスタートアップディレクトリを見つけるにはどうすればよいですか?
また、呼び出し元モジュールへのパスを取得する別の方法がありますか?
私はこの取得Jean-François Fabre's answer
for file,line,w1,w2 in traceback.extract_stack():
sys.stdout.write(' File "{}", line {}, in {}\n'.format(file,line,w1))
を実行する場合:
File "c:\app\python\anaconda\1.6.0\Scripts\sphinx-build-script.py", line 5, in <module>
File "c:\app\python\anaconda\1.6.0\lib\site-packages\Sphinx-1.4.1-py2.7.egg\sphinx\__init__.py", line 51, in main
File "c:\app\python\anaconda\1.6.0\lib\site-packages\Sphinx-1.4.1-py2.7.egg\sphinx\__init__.py", line 92, in build_main
File "c:\app\python\anaconda\1.6.0\lib\site-packages\Sphinx-1.4.1-py2.7.egg\sphinx\cmdline.py", line 243, in main
File "c:\app\python\anaconda\1.6.0\lib\site-packages\Sphinx-1.4.1-py2.7.egg\sphinx\application.py", line 155, in __init__
File "conf.py", line 512, in setup
[more lines elided, the conf.py is the one that matters]
をので、問題は、私はconf.py
へのパスを見つける必要があるが、現在のディレクトリはによって変更されたということですスフィンクスだから私はできないよos.path.abspath(caller_filename)
'os.getcwd()'のpythonは '__file__'は「私はあなたが何を意味を知らない...あなたはそれ以外の –
をどんなの.pyファイルのパスとファイル名を教えてくれます実行されているディレクトリです起動ディレクトリ " –
"ですが、私はこのファイル名をいくつかのディレクトリのコンテキストで解釈する必要があります。 "どういう意味ですか? –