You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Bash脚本自动化在服务器上创建多个运行指定Python脚本的tmux会话?

Hey there! I totally get how draining that repetitive manual process is—let’s automate this so you can save time and avoid the Ctrl+B+D grind. Here are a couple of straightforward solutions tailored for someone new to server/tmux workflows:

1. Quick One-Liner for Immediate Use

If you just need to spin up a set number of sessions right away, you can run this directly in your terminal. Let’s say you want 5 sessions (adjust the number in {1..5} as needed):

for i in {1..5}; do
  tmux new-session -d -s "xshares_$i" 'cd /path/to/your/python/folder && python3 xshares.py'
done

Breakdown of the command:

  • tmux new-session -d: Creates a new tmux session in the background (so you don’t get pulled into it immediately)
  • -s "xshares_$i": Names each session uniquely (e.g., xshares_1, xshares_2) to keep things organized
  • The quoted command 'cd ... && python3 xshares.py': Runs exactly what you’d do manually—navigates to your script directory, then launches the Python script

For a more robust solution that checks for existing sessions (so you don’t accidentally create duplicates), create a shell script:

  1. Create a new file (e.g., start_xshares_sessions.sh) with this content:
#!/bin/bash

# Configure these variables to match your setup
PYTHON_SCRIPT_DIR="/absolute/path/to/your/python/directory"
NUMBER_OF_SESSIONS=5
SESSION_NAME_PREFIX="xshares_run"

# Loop to create sessions
for ((i=1; i<=NUMBER_OF_SESSIONS; i++)); do
  SESSION_NAME="${SESSION_NAME_PREFIX}_$i"
  
  # Check if the session already exists to avoid duplicates
  if ! tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
    tmux new-session -d -s "$SESSION_NAME" "cd $PYTHON_SCRIPT_DIR && python3 xshares.py"
    echo "✅ Created session: $SESSION_NAME"
  else
    echo "⚠️ Session $SESSION_NAME already exists—skipping"
  fi
done
  1. Make the script executable:
chmod +x start_xshares_sessions.sh
  1. Run it whenever you need to spin up sessions:
./start_xshares_sessions.sh

Bonus Tips for Managing Sessions

  • List all active tmux sessions: tmux ls
  • Attach to a specific session (e.g., xshares_run_3): tmux attach -t xshares_run_3
  • Kill a specific session: tmux kill-session -t xshares_run_3
  • Kill all sessions with the prefix: for i in {1..5}; do tmux kill-session -t xshares_run_$i; done

If You Use a Virtual Environment

If your Python script relies on a virtual environment, update the command inside the tmux session to activate it first:

"cd $PYTHON_SCRIPT_DIR && source venv/bin/activate && python3 xshares.py"

Just replace venv with your virtual environment folder name.

内容的提问来源于stack exchange,提问作者xtekky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 18:12:45