【问题标题】:How to run python file inside tmux session?如何在 tmux 会话中运行 python 文件?
【发布时间】:2018-08-26 13:36:30
【问题描述】:

我正在尝试在tmux 会话中运行 python 脚本。我写了一个命令 (tmux new-session -d -s my_session),它从 crontab 运行良好。

但是当我尝试使用tmux new-session -d -s my_session 'python3 test.pytmux new-session -d -s my_session 'sh test.sh 运行python 或shell 文件时 脚本不运行。我使用了来自here 的参考。 请帮我解决这个问题。

【问题讨论】:

    标签: linux python-3.x cron tmux


    【解决方案1】:

    编辑
    您可以使用\; 分隔tmux 命令,然后使用send-keys 命令将命令发送到活动窗口。
    在您的情况下,您可以使用:

    tmux new-session -d -s my_session \; send-keys "python3 test.py" Enter
    tmux new-session -d -s my_session \; send-keys "sh test.sh" Enter
    tmux new-session -d -s my_session \; send-keys "python3 -m http.server 8080" Enter
    

    您可以在tmux manpages section for send-keys 上找到有关send-keys 选项的更多信息:

    send-keys [-lMRX] [-N repeat-count] [-t target-窗格] 键 ...
    (别名:发送
    将一个或多个键发送到窗口。每个参数键是要发送的键的名称(例如'C-a'或'NPage');如果字符串未被识别为键,则将其作为一系列字符发送。 -l 标志禁用键名查找并按字面意思发送键。所有参数从第一个到最后一个顺序发送。 -R 标志导致终端状态被重置。

    -M 传递鼠标事件(仅在绑定到鼠标键绑定时有效,参见MOUSE SUPPORT)。
    -X 用于发送进入复制模式的命令 - 请参阅 WINDOWS AND PANES 部分。
    -N 指定重复计数。

    send-keys 语法在tmux manpageKey Bindings section 上进行了描述。 send-keys 使用的键名与bind-key 使用的键名相同。

    我通常在基础文件之上使用不同的配置文件。

    假设您在~/.tmux.conf 中有您的tmux 配置,然后我在~/.tmux/ 文件夹中创建不同的配置文件。例如,我可以有一个 python 配置文件(如果你想进入会话,请使用attach):

    # To use this configuration launch tmux with the command:
    #   > tmux -f ~/.tmux/python.conf attach
    #
    
    # Load default tmux config
    source-file ~/.tmux.conf
    
    # Create session and launch python script
    new-session -s python -n python -d -c ~/src/python/
    send-keys "python test.py" Enter
    

    这让我可以灵活地创建更复杂的会话。

    【讨论】:

    • 我试过这个 tmux new-session -d -s myTempSession sh runPython.sh 但这没有用。以及 ~/.tmux.conf` 我如何创建它。请指导。
    • 这是您自定义的 tmux 配置,如果您没有使用,您可以简单地评论该行。
    • 酷,但是这个反引号“`”不起作用。你能查一下吗?
    • 对不起,你是对的,后面的滴答声肯定不起作用!我已经使用 \; 更正了答案以及在新创建的 tmux 会话中执行命令的发送密钥。这就是你要找的东西吗?
    • 这就像一个魅力。非常感谢。有什么参考资料可以让我学习send-keys 和其他关于 tmux 及其语法的东西吗?
    猜你喜欢
    • 2019-07-17
    • 2021-03-08
    • 1970-01-01
    • 2021-11-27
    • 2012-05-05
    • 2012-01-21
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多