python - 设置sqlite临时存储目录

标签 python sqlite

我有一个 Python 二进制文件,它使用 SQLite 作为其后端数据库。 SQLite 的文档和代码建议设置以下 3 个环境变量中的任何一个都应该有效:

export TMP=/var/tmp/sqlite/
export TEMP=/var/tmp/sqlite/
export TEMPDIR=/var/tmp/sqlite/

如果我在启动 Python 二进制文件之前在我的 bash 脚本中导出上述变量,这没有帮助。

我尝试的另一个选项是通过设置 os.environ 调用 putenv():

os.environ['TMP'] = /var/tmp/sqlite/
os.environ['TEMP'] = /var/tmp/sqlite/
os.environ['TEMPDIR'] = /var/tmp/sqlite/

以上选项都没有帮助说服 SQLite 使用 /var/tmp/sqlite 作为其临时存储目录。唯一可行的选项(SQLite 的文档称已弃用)是设置 temp_store_directory pragma 语句:

PRAGMA temp_store_directory = '/egnyte/.work/sqlite_temp'

既然使用pragma语句不是我愿意做出的选择,那么还有其他技巧吗?

最佳答案

您所指的环境变量确实是 sqlite 寻找的,但在 Windows 中,而不是 UNIX。

在 Unix 中,您需要设置的环境变量是 TMPDIR,如源代码所示:

static const char *unixTempFileDir(void){
  static const char *azDirs[] = {
     0,
     0,
     "/var/tmp",
     "/usr/tmp",
     "/tmp",
     0        /* List terminator */
  };
  unsigned int i;
  struct stat buf;
  const char *zDir = 0;

  azDirs[0] = sqlite3_temp_directory;
  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
    if( zDir==0 ) continue;
    if( osStat(zDir, &buf) ) continue;
    if( !S_ISDIR(buf.st_mode) ) continue;
    if( osAccess(zDir, 07) ) continue;
    break;
  }
  return zDir;
}

关于python - 设置sqlite临时存储目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10394517/

相关文章:

python - 线程安全等效于 python 的 time.strptime()?

iphone - PDF iOS 应用程序的离线存储

iphone - iPhone 上的 SQLite 表无效?

python - 如何从不带引号的文件加载嵌套列表?

python - 使用 pip 命令从 requirements.txt 升级 python 包

php - MySQL 和 SqLite - 兼容时间戳比较

python - 升级到 Peewee 2.6 后出现 sqlite3 InterfaceError

ruby - 在 Ubuntu 上安装 dm-sqlite-adapter 错误

python - Manim:在现有对象后面创建对象(在创建时强制 z-index)

python - 如何维护 PhotoImage 对象的多个引用