Cách chạy file Python trên Linux, Ubuntu, CentOS

Thảo luận trong 'Kiến Thức' bắt đầu bởi Bill Gates, 21 Tháng ba 2025.

  1. Bill Gates

    Bài viết:
    3
    Cách triển khai BOT lên server Ubuntu

    Bước 1: Kiểm tra và cài đặt Python3 nếu chưa có, sử dụng hệ điều hành CentOS, nếu hệ điều hành khác câu lệnh có thể hơi khác một chút.

    Mã:
    sudo yum install -y python3
    Dưới đây là các cách phổ biến để chạy một script Python trên CentOS. Bạn chọn phương án phù hợp với nhu cầu:

    Chạy script bằng tay:

    Mã:
    python3 /đường/dẫn/đến/script.py
    Chạy ngầm background

    Lệnh nohup:

    Mã:
    nohup python3 script.py > script.log 2>&1 &
    Hoặc screen:

    Mã:
    sudo yum install -y screen
    screen -S myscript
    python3 script.py
    # Nhấn Ctrl+A rồi D để detach
    screen -r myscript  # để attach lại

    Tự khởi động cùng hệ thống


    Dùng cron @reboot

    Mã:
    crontab -e
    # Thêm:
    @reboot /usr/bin/python3 /path/to/script.py >> /path/to/log.log 2>&1

    Dùng systemd

    Tạo file /etc/systemd/system/mybot.service:

    Mã:
    ini
    [Unit]
    Description=My Python Script
    
    [Service]
    ExecStart=/usr/bin/python3 /path/to/script.py
    WorkingDirectory=/path/to
    Restart=on-failure
    User=root
    
    [Install]
    WantedBy=multi-user.target
    Nhớ thay path/to bằng đường dẫn và User=root đúng máy của bạn nhé

    Reload và enable:

    Mã:
    sudo systemctl stop mybot.service
    
    sudo systemctl daemon-reexec
    sudo systemctl daemon-reload
    sudo systemctl enable --now mybot.service
    sudo systemctl enable mybot.service
    sudo systemctl restart mybot.service
    sudo systemctl start mybot.service
    Nếu lỗi thử:

    Mã:
    sudo systemctl enable mybot.service
    Kiểm tra trạng thái:

    Mã:
    systemctl status mybot.service
    Tạm dừng bot:

    Mã:
    sudo systemctl stop mybot.service
     
    Last edited by a moderator: 5 Tháng năm 2025
Từ Khóa:
Trả lời qua Facebook
Đang tải...