Nohup在终止之前不会打印到标准输出

25 浏览
0 Comments

Nohup在终止之前不会打印到标准输出

我有一个类似以下的Python脚本:

#!/usr/bin/env python
print("开始")
sql = get_sql_from_file(...)
# 以下函数运行时间较长
execute_oracle_driver(sql)
print("完成")

我用以下命令执行它:

(my-env) $ time nohup python script.py &

然后我检查是否有任何初始输出,但什么都没有:

(my-env) $ cat nohup.out
(my-env) $ 

我至少期望在几秒钟内看到"开始"。即使等待几分钟后将其终止,也没有任何输出。如果可能的话,我该如何修复这个问题?

0
0 Comments

Nohup is a command in Unix-like operating systems that allows a user to run a command or script in the background even after the user logs out. It is often used to ensure that a process continues running even if the user's connection is terminated.

One issue that can arise when using Nohup is that the output of the command or script may not be immediately visible. This is because the output is buffered by default, meaning that it is stored in memory before being written to the designated output file, usually named "nohup.out". As a result, the output will not be seen in "nohup.out" until the program terminates.

To solve this issue and ensure that the output is immediately visible, you can use the "flush" option when printing. By using the "flush=True" argument in the print statement, the output will be immediately flushed to the output file, bypassing the default buffering.

Here is an example in Python:

print("Start", flush=True)

This line of code will print "Start" to stdout and immediately flush it to the output file. As a result, the output will be visible in "nohup.out" as soon as it is printed.

It is important to note that this issue has been asked and answered many times before. When providing answers on platforms like Stack Overflow, it is recommended to refer to the guidelines for answering well-asked questions. In particular, it is important to acknowledge that the question has been asked and answered before, and provide a concise and clear solution to the problem.

0