如何使用 Fabric 通过 nohup 启动后台进程?

发布于 2024-12-25 15:39:24 字数 567 浏览 1 评论 0原文

通过 Fabric,我尝试使用下面的 nohup 命令启动 celerycam 进程。不幸的是,什么也没发生。手动使用相同的命令,我可以启动该进程,但不能通过 Fabric。关于如何解决这个问题有什么建议吗?

def start_celerycam():
    '''Start celerycam daemon'''
    with cd(env.project_dir):
        virtualenv('nohup bash -c "python manage.py celerycam --logfile=%scelerycam.log --pidfile=%scelerycam.pid &> %scelerycam.nohup &> %scelerycam.err" &' % (env.celery_log_dir,env.celery_log_dir,env.celery_log_dir,env.celery_log_dir))

        

Through Fabric, I am trying to start a celerycam process using the below nohup command. Unfortunately, nothing is happening. Manually using the same command, I could start the process but not through Fabric. Any advice on how can I solve this?

def start_celerycam():
    '''Start celerycam daemon'''
    with cd(env.project_dir):
        virtualenv('nohup bash -c "python manage.py celerycam --logfile=%scelerycam.log --pidfile=%scelerycam.pid &> %scelerycam.nohup &> %scelerycam.err" &' % (env.celery_log_dir,env.celery_log_dir,env.celery_log_dir,env.celery_log_dir))

        

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

探春 2025-01-01 15:39:24

我正在使用 Erich Heine 的建议来使用“dtach”,它对我来说效果很好:

def runbg(cmd, sockname="dtach"):
    return run('dtach -n `mktemp -u /tmp/%s.XXXX` %s' % (sockname, cmd))

发现了 此处

I'm using Erich Heine's suggestion to use 'dtach' and it's working pretty well for me:

def runbg(cmd, sockname="dtach"):
    return run('dtach -n `mktemp -u /tmp/%s.XXXX` %s' % (sockname, cmd))

This was found here.

影子的影子 2025-01-01 15:39:24

正如我所试验的,解决方案是两个因素的组合:

  • 作为守护进程运行进程: nohup ./command &> /dev/null &
  • 使用 pty=False 进行结构运行

因此,您的函数应该如下所示:

def background_run(command):
    command = 'nohup %s &> /dev/null &' % command
    run(command, pty=False)

您可以使用以下命令启动它:

execute(background_run, your_command)

As I have experimented, the solution is a combination of two factors:

  • run process as a daemon: nohup ./command &> /dev/null &
  • use pty=False for fabric run

So, your function should look like this:

def background_run(command):
    command = 'nohup %s &> /dev/null &' % command
    run(command, pty=False)

And you can launch it with:

execute(background_run, your_command)
我爱人 2025-01-01 15:39:24

这是此问题的一个实例。当命令结束时,后台进程将被终止。不幸的是,CentOS 6 不支持 pty-less sudo 命令。

该问题的最后一个条目提到使用 sudo('set -m; service servicename start')。这将打开作业控制,因此后台进程将被放入其自己的进程组中。因此,当命令结束时它们不会终止。

有关更多信息,请参阅 链接。

This is an instance of this issue. Background processes will be killed when the command ends. Unfortunately on CentOS 6 doesn't support pty-less sudo commands.

The final entry in the issue mentions using sudo('set -m; service servicename start'). This turns on Job Control and therefore background processes are put in their own process group. As a result they are not terminated when the command ends.

For even more information see this link.

青芜 2025-01-01 15:39:24

你只需要跑

run("(nohup yourcommand >& /dev/null < /dev/null &) && sleep 1")

you just need to run

run("(nohup yourcommand >& /dev/null < /dev/null &) && sleep 1")
二货你真萌 2025-01-01 15:39:24

DTACH 是必经之路。这是一个需要像精简版 screen 一样安装的软件。
这是上面找到的“dtach”方法的更好版本,如果需要,它将安装 dtach。您可以在此处找到它了解如何获取在后台运行的进程的输出:

from fabric.api import run
from fabric.api import sudo
from fabric.contrib.files import exists


def run_bg(cmd, before=None, sockname="dtach", use_sudo=False):
    """Run a command in the background using dtach

    :param cmd: The command to run
    :param output_file: The file to send all of the output to.
    :param before: The command to run before the dtach. E.g. exporting
                   environment variable
    :param sockname: The socket name to use for the temp file
    :param use_sudo: Whether or not to use sudo
    """
    if not exists("/usr/bin/dtach"):
        sudo("apt-get install dtach")
    if before:
        cmd = "{}; dtach -n `mktemp -u /tmp/{}.XXXX` {}".format(
            before, sockname, cmd)
    else:
        cmd = "dtach -n `mktemp -u /tmp/{}.XXXX` {}".format(sockname, cmd)
    if use_sudo:
        return sudo(cmd)
    else:
        return run(cmd)

希望这可以帮助您,就像它帮助我通过远程 rasberry pi 上的 Fabric 运行 omxplayer 一样!

DTACH is the way to go. It's a software you need to install like a lite version of screen.
This is a better version of the "dtach"-method found above, it will install dtach if necessary. It's to be found here where you can also learn how to get the output of the process which is running in the background:

from fabric.api import run
from fabric.api import sudo
from fabric.contrib.files import exists


def run_bg(cmd, before=None, sockname="dtach", use_sudo=False):
    """Run a command in the background using dtach

    :param cmd: The command to run
    :param output_file: The file to send all of the output to.
    :param before: The command to run before the dtach. E.g. exporting
                   environment variable
    :param sockname: The socket name to use for the temp file
    :param use_sudo: Whether or not to use sudo
    """
    if not exists("/usr/bin/dtach"):
        sudo("apt-get install dtach")
    if before:
        cmd = "{}; dtach -n `mktemp -u /tmp/{}.XXXX` {}".format(
            before, sockname, cmd)
    else:
        cmd = "dtach -n `mktemp -u /tmp/{}.XXXX` {}".format(sockname, cmd)
    if use_sudo:
        return sudo(cmd)
    else:
        return run(cmd)

May this help you, like it helped me to run omxplayer via fabric on a remote rasberry pi!

梦情居士 2025-01-01 15:39:24

您可以使用:

run('nohup /home/ubuntu/spider/bin/python3 /home/ubuntu/spider/Desktop/baidu_index/baidu_index.py > /home/ubuntu/spider/Desktop/baidu_index/baidu_index.py.log 2>&1 &', pty=False)

You can use :

run('nohup /home/ubuntu/spider/bin/python3 /home/ubuntu/spider/Desktop/baidu_index/baidu_index.py > /home/ubuntu/spider/Desktop/baidu_index/baidu_index.py.log 2>&1 &', pty=False)
凉墨 2025-01-01 15:39:24

nohup 对我来说不起作用,而且我没有在我想使用它的所有盒子上安装 tmuxdtach,所以我最终像这样使用 screen

run("screen -d -m bash -c '{}'".format(command), pty=False)

这告诉 screen 在运行命令的独立终端中启动 bash shell

nohup did not work for me and I did not have tmux or dtach installed on all the boxes I wanted to use this on so I ended up using screen like so:

run("screen -d -m bash -c '{}'".format(command), pty=False)

This tells screen to start a bash shell in a detached terminal that runs your command

海拔太高太耀眼 2025-01-01 15:39:24

您可能会遇到此问题

尝试添加 'pty=False ' 到 sudo 命令(我假设 virtualenv 正在调用 sudo 或在某个地方运行?)

You could be running into this issue

Try adding 'pty=False' to the sudo command (I assume virtualenv is calling sudo or run somewhere?)

无名指的心愿 2025-01-01 15:39:24

这对我有用:

sudo('python %s/manage.py celerycam --detach --pidfile=celerycam.pid' % siteDir)

编辑:我必须确保首先删除 pid 文件,所以这是完整的代码:

# Create new celerycam
sudo('rm celerycam.pid', warn_only=True)
sudo('python %s/manage.py celerycam --detach --pidfile=celerycam.pid' % siteDir)

This worked for me:

sudo('python %s/manage.py celerycam --detach --pidfile=celerycam.pid' % siteDir)

Edit: I had to make sure the pid file was removed first so this was the full code:

# Create new celerycam
sudo('rm celerycam.pid', warn_only=True)
sudo('python %s/manage.py celerycam --detach --pidfile=celerycam.pid' % siteDir)
不气馁 2025-01-01 15:39:24

我能够通过在单独的本地 shell 脚本中通过 ssh 运行 nohup ... & 来规避此问题。在 fabfile.py 中:

@task
def startup():
    local('./do-stuff-in-background.sh {0}'.format(env.host))

和在 do-stuff-in-background.sh 中:

#!/bin/sh

set -e
set -o nounset

HOST=$1

ssh $HOST -T << HERE
   nohup df -h 1>>~/df.log 2>>~/df.err &
HERE

当然,您也可以传入命令和标准输出/错误日志文件作为参数使这个脚本更普遍有用。

(就我而言,我没有安装 dtach 的管理员权限,也没有 screen -d -mpty=False / < code>sleep 1 对我来说工作正常,尤其是我不知道为什么它有效......)

I was able to circumvent this issue by running nohup ... & over ssh in a separate local shell script. In fabfile.py:

@task
def startup():
    local('./do-stuff-in-background.sh {0}'.format(env.host))

and in do-stuff-in-background.sh:

#!/bin/sh

set -e
set -o nounset

HOST=$1

ssh $HOST -T << HERE
   nohup df -h 1>>~/df.log 2>>~/df.err &
HERE

Of course, you could also pass in the command and standard output / error log files as arguments to make this script more generally useful.

(In my case, I didn't have admin rights to install dtach, and neither screen -d -m nor pty=False / sleep 1 worked properly for me. YMMV, especially as I have no idea why this works...)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文