Better solution for MAIN_DIR: read out sys.argv

This commit is contained in:
rdb 2009-07-19 09:52:43 +00:00
parent 563bd81b68
commit 36d663ff98
3 changed files with 28 additions and 6 deletions

View File

@ -35,6 +35,10 @@
#define environ (*_NSGetEnviron())
#endif
#ifdef HAVE_PYTHON
#include "Python.h"
#endif
// We define the symbol PREREAD_ENVIRONMENT if we cannot rely on
// getenv() to read environment variables at static init time. In
// this case, we must read all of the environment variables directly
@ -205,6 +209,26 @@ ns_get_environment_variable(const string &var) const {
return Filename::get_user_appdata_directory().to_os_specific();
} else if (var == "COMMON_APPDATA") {
return Filename::get_common_appdata_directory().to_os_specific();
} else if (var == "MAIN_DIR") {
#ifdef HAVE_PYTHON
// If we're running from Python code, read out sys.argv.
if (PyObject* obj = PySys_GetObject((char*) "argv")) {
Filename main_dir (PyString_AsString(PyList_GetItem(obj, 0)));
if (main_dir.empty()) {
// We must be running in the Python interpreter directly, so return the CWD.
return get_cwd();
}
main_dir.make_absolute();
return Filename(main_dir.get_dirname()).to_os_specific();
}
#endif
// Otherwise, Return the binary name's parent directory.
if (!_binary_name.empty()) {
Filename main_dir (_binary_name);
main_dir.make_absolute();
return Filename(main_dir.get_dirname()).to_os_specific();
}
}
#ifdef PREREAD_ENVIRONMENT
@ -551,10 +575,6 @@ read_args() {
}
#endif
if (!_binary_name.empty()) {
ns_set_environment_variable("MAIN_DIR", Filename(_binary_name).get_dirname());
}
if (_dtool_name.empty()) {
_dtool_name = _binary_name;
}

View File

@ -527,8 +527,8 @@ scan_auto_prc_dir(Filename &prc_dir) const {
return true;
}
// Try the current working directory.
dir = ExecutionEnvironment::get_cwd();
// Try the program's directory.
dir = ExecutionEnvironment::get_environment_variable("MAIN_DIR");
if (scan_up_from(prc_dir, dir, suffix)) {
return true;
}

View File

@ -96,6 +96,7 @@ extern "C" {
EXPCL_DTOOLCONFIG int PyString_FromString(...);
EXPCL_DTOOLCONFIG int PyString_FromStringAndSize(...);
EXPCL_DTOOLCONFIG int PyString_Type(...);
EXPCL_DTOOLCONFIG int PySys_GetObject(...);
EXPCL_DTOOLCONFIG int PyThreadState_Clear(...);
EXPCL_DTOOLCONFIG int PyThreadState_Delete(...);
EXPCL_DTOOLCONFIG int PyThreadState_Get(...);
@ -223,6 +224,7 @@ int PyString_AsStringAndSize(...) { return 0; }
int PyString_FromString(...) { return 0; }
int PyString_FromStringAndSize(...) { return 0; }
int PyString_Type(...) { return 0; }
int PySys_GetObject(...) { return 0; }
int PyThreadState_Clear(...) { return 0; }
int PyThreadState_Delete(...) { return 0; }
int PyThreadState_Get(...) { return 0; }