如何从命令行获取一个持久的Python会话?

3

我希望通过Shell实现以下行为:

$ python --new-session -c ''
$ python --use-session -c 'x = 42'
$ python --use-session -c 'print x'
42

为什么要这样做?

我在使用命令行中的许多助手,例如 mako-renderjinja 等来生成我的(C/C++)项目文件。每次 Python 调用时,所有使用的模块都需要导入到工作区,这需要时间。通过在我的 Python 调用之间使用持久化的工作区,可以节省大量处理时间。

我的当前解决方案是使用 shelve 在我的会话之间存储所有可以存储的内容,但这并不方便,我正在寻找一个不那么复杂的解决方案。

我知道使用 Jupyter 内核可以做到这一点。不幸的是,在我的系统上启动一个连接到现有内核的新 Python 会话需要约 5 到 10 秒钟的时间。

1个回答

2
以下bash脚本是你所需的草稿近似版本:

python-session:


以下是需要翻译的内容。
#!/usr/bin/env bash

if [[ $# -ne 1 ]]
then
    echo 1>&2 "Usage: python-session <session-name>"
    exit 1
fi

sessionname="$1"
sessiondir=/tmp/python-session."$sessionname"
stdin="$sessiondir/stdin"
stdout="$sessiondir/stdout"

endsession()
{
    echo Exiting python session "$sessionname"
    rm -rf "$sessiondir"
}

newsession()
(
    echo "Starting new session $sessionname"
    mkdir "$sessiondir"
    trap "endsession" EXIT
    touch "$stdin"
    touch "$stdout"
    tail -f "$stdin"|python -i -c "import sys; sys.ps1=sys.ps2=''">"$stdout"
)

if [ ! -d "$sessiondir" ]
then
    newsession & disown
    while [ ! -e "$stdout" ]; do sleep 0.01; done
fi

echo "Connected to python session $1 (leave the session by typing CTRL-D)"
tail -f -n 0 "$stdout"&
tailpid=$!
trap "kill $tailpid" EXIT
cat >> "$stdin"

演示:

$ ./python-session 1
Starting new session 1
Connected to python session 1 (leave the session by typing CTRL-D)
x=123
$ ./python-session 1
Connected to python session 1 (leave the session by typing CTRL-D)
print x
123
$ ./python-session 2
Starting new session 2
Connected to python session 2 (leave the session by typing CTRL-D)
print x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
x='abc'
$ ./python-session 1
Connected to python session 1 (leave the session by typing CTRL-D)
print x
123
$ ./python-session 2
Connected to python session 2 (leave the session by typing CTRL-D)
print x
abc
exit()

Exiting python session 2
$ ./python-session 1
Connected to python session 1 (leave the session by typing CTRL-D)
exit()

Exiting python session 1
$

草案实现的限制

  • 你必须通过输入exit()命令 后面跟着一行额外的(即使是空的)内容 来停止会话。之后,你仍然需要按下CTRL-D来断开从现在不存在的会话中获得的连接。

  • Python会话的标准错误流没有被捕获。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接