Skip to main content
 首页 » 编程设计

python之在后台时卡住标准输入,在前台时解冻它

2025年05月04日15yjmyzz

我正在尝试在后台运行脚本:

nohup script.py > out 2> err < /dev/null & 

脚本(Python 3.4)在某些时候做:

answer = input('? ') 

(它有一个在其中一个线程中运行的菜单)

nohup 调用崩溃了:

EOFError: EOF when reading a line 

我想是因为 stdin 的 /dev/null 重定向。如果我在没有 stdin 重定向的情况下运行它:

nohup script.py > out 2> err & 

它崩溃了:

OSError: [Errno 9] Bad file descriptor 

如果我运行它:

script.py > out 2> err 

它可以工作,但会阻塞我的终端(它在前台)

如果我运行它:

script.py > out 2> err & 

它在后台运行正常,但一旦到达 input 调用就会停止。

我想要的是:

  • 能够将stdout 和stderr 重定向到文件系统
  • 能够将脚本置于后台
  • 能够将 if 移动到前台并正常与菜单交互(因此必须以某种方式启用 stdin)。 stdout 和 stderr 仍会被重定向到文件系统,但 stdin 会正常运行。
  • 脚本必须在后台和前台都能正常运行(当然,菜单在后台不起作用,因为 stdin 被“卡住”)

基本上,我想要的是,当它在后台时,stdin 有点“卡住”,而当它进入前台时,它会再次正常工作。

这可能吗?解决方案不需要涉及nohup

请您参考如下方法:

你想要什么(以及 input 如何在 python 下的 EOF 上工作和失败)与交互式菜单意味着你不能安全地传递一个文件作为 stdin 调用程序时。这意味着您唯一的选择是像这样调用它:

$ script.py > out 2> err & 

作为演示,这是我的脚本:

from time import sleep 
import sys 
 
c = 0 
while True: 
    sleep(0.001) 
    c += 1 
    if c % 1000 == 0: 
        print(c, flush=True) 
    if c % 2000 == 0: 
        print(c, file=sys.stderr, flush=True) 
    if c % 10000 == 0: 
        answer = input('? ') 
        print('The answer is %s' % answer, flush=True) 

基本上,每秒它会写入stdout,每两秒它会写入stderr,最后,每十秒它会等待输入。如果我要运行它并等待几秒钟(以允许磁盘刷新),然后将它们链接在一起,就像这样:

$ python script.py > out 2> err & sleep 2.5; cat out err 
[1] 32123 
1000 
2000 
2000 
$  

等待至少 10 秒,然后再次尝试 cat out err:

$ cat out err 
1000 
2000 
3000 
4000 
5000 
6000 
7000 
8000 
9000 
10000 
? 2000 
4000 
6000 
8000 
10000 
 
[1]+  Stopped                 python script.py > out 2> err 
$  

请注意,input 生成的提示也写入了 stdout,程序有效地继续运行到它期望 stdin 为其提供数据的位置。您只需按 % 将进程带回前台,并开始向其提供所需的数据,然后使用 ^Z (Ctrl< kbd>Z) 并使用 %& 让它在后台再次运行。示例:

$ % 
python script.py > out 2> err 
Test input 
^Z 
[1]+  Stopped                 python script.py > out 2> err 
$ %& 
[1]+ python script.py > out 2> err & 
$ 

再等 10 秒后,现在再次 cat out:

$ cat out 
1000 
... 
10000 
? The answer is Test input 
11000 
... 
20000 
?  
[1]+  Stopped                 python script.py > out 2> err 
$ 

这本质上是一个基本的速成类(class),介绍标准进程通常如何在前台和后台运行,如果代码正确处理标准 IO,事情就会按预期工作。

最后,您不能真正兼顾两者。如果应用程序需要 stdin 而未提供,则清除选项失败。但是,如果提供了一个但应用程序已发送到后台并继续运行,它将被 Stopped 因为它需要进一步的输入。如果这种停止行为是不需要的,则应用程序有问题,除了将应用程序更改为在使用 /dev/执行时遇到 EOF 时不会导致错误外,别无他法null 作为它的 stdin。如果你想保持 stdin 不变,当应用程序在后台时能够以某种方式继续运行,你不能使用 input 函数,因为它会在 stdin 为空(导致进程停止)。


现在您已经通过下面的评论澄清了您的“交互式提示”正在线程中运行,并且由于 input 的使用直接从 stdin 读取并且您似乎不愿意修改您的程序(您要求一般情况)但希望实用程序为您执行此操作,简单的解决方案是在 tmux 中执行此操作或 screen session 因为他们完全实现了一个伪 tty,它独立于启动的任何控制台(因此您可以断开连接并将 session 发送到后台,或启动其他虚拟 session ,请参阅手册页),它将提供程序期望的 stdio。

最后,如果您真的希望您的应用程序本身就支持它,您不能简单地按原样使用 input,但您应该检查是否可以安全地调用 input(即也许使用 select ),或者通过检查进程当前是在前台还是后台(您可以从 How to detect if python script is being run as a background process 开始工作的示例,尽管您可能想使用 sys.stdin, maybe.) 来确定是否可以安全地调用 input (但是如果用户在输入到来时暂停任务,它仍然会在 input 等待时挂起),或者使用 unix用于通信的套接字。