python - Bash 脚本未使用 nohup 在后台运行

标签 python linux bash background-process nohup

我有一个 bash 脚本,它激活 anaconda 环境并运行 python 调度程序脚本并每分钟将日志写入文件。如果我只运行脚本,它工作得很好。

[user@host proj]$ test.sh

执行 ctrl-C 后,我看到日志每分钟都会出现。

[user@host proj]$ cat logs/log.log
Test job 1 executed at : 2018-10-09 14:16:00.000787
Test job 1 executed at : 2018-10-09 14:17:00.001890
Test job 1 executed at : 2018-10-09 14:18:00.001861

但是当我使用 nohup 在后台运行相同的脚本时

[user@host proj]$ nohup test.sh &
[1] 24884
[user@host proj]$ nohup: ignoring input and appending output to ‘nohup.out’

我可以通过 top 看到脚本和 python 正在运行

24949 user  20   0  113172   1444   1216 S  0.0  0.0   0:00.00 test.sh
24952 user  20   0  516332  66644  17344 S  0.0  0.8   0:00.65 python

但是我看不到日志文件中要写入的任何内容。

不知道出了什么问题。非常感谢任何指导我正确方向的建议。

最佳答案

我假设 proj 目录位于您的 PATH 变量中。

如果 nohup.out 中没有打印任何内容,那么我认为您没有任何内容可以回显到 nohup.out 文件。如果您使用的是 bash,请尝试在 shebang 行下方使用 set -xv ,即 #/bin/bash 。现在,在运行 shell 脚本时,nohup 将至少有一个您从 shell 脚本运行的 python 脚本的条目,如下所示。

user@host:~/scripts$ cat nohup.out

python/home/madbala/scripts/append_file.py + python/home/madbala/scripts/append_file.py

我尝试重现您的情况如下:

  1. Python 脚本名称(抱歉,我对 python 不太了解):append_file.py

    #!/usr/bin/python
    from datetime import datetime
    import time
    with open("test.txt", "a") as myfile:
       for x in range(15):
          myfile.write('appended text %s \n' %datetime.now())
          time.sleep(2)
    
  2. 调用上述Python脚本的Shell脚本:run_py_script.sh

      #!/bin/bash
      set -xv
      python /home/madbala/scripts/append_file.py
    

现在运行 nohup run_py_script.sh & 我得到了输出,因为我有 set -xv (这实际上在 shell 脚本中启用了详细日志记录 - 您也可以只使用 set -x)。

当我使用 #set -xv 注释掉 set -xv 时,nohup.out 将没有内容。

Screenshot

关于python - Bash 脚本未使用 nohup 在后台运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52729207/

相关文章:

python - OpenCV 误差校准教程 (solvePnPRansac)

linux - Linux 中的 CoqIDE 配置

bash - 在命令替换中使用引号

python - 如何将数以百万计的联系人添加到 Telegram ?

python - 按列值中的字符串删除行

python - 在 linux 中执行远程命令时如何处理错误

linux - 在 Linux 2.6 驱动程序模块 makefile 中创建调试目标

php - 如何在 CentOS 6.2 上安装 PHP mbstring

linux - 如何使用 shell 脚本中的选项和参数启动自定义二进制文件

bash - 使用符号链接(symbolic link)时 sh 和 bash 之间的区别