Bash at和$ DISPLAY,howto?

时间:2014-03-21 16:41:30

标签: python bash environment

我正在开发一个Python GUI应用程序,在某些时候我需要推迟执行Python代码的大部分内容。我尝试使用at来执行此操作:

line = 'echo "python ./executor.py ibm ide graph" | at -t 1403211632'
subprocess.Popen(line,Shell=True)

这一行没有错误,并且在给定时间有效地启动了作业。

现在,executor.py的每个选项都是它必须完成的工作,每个作业都受到try / catch日志的保护。在某些情况下,我发现了这个错误:

14-03-21_17:07:00 starting ibm for Simulations/140321170659
Failed to execute ibm : no display name and no $DISPLAY environment variable
Aborted the whole execution.

我尝试过以下方法,以为我可以向环境提供$ DISPLAY,但没有成功(同样的错误):

line = 'DISPLAY=:0.0;echo "python ./executor.py Simulations/140321170936 eid defer" | at -t 1403211711'

来自man at

The working  directory, the environment (except for the variables BASH_VERSINFO, DISPLAY, EUID, GROUPS, SHELLOPTS, TERM, UID, and _) and the umask are retained from the time of invocation.

问题:

  • 可能导致此错误的原因是什么?
  • 如何向at的环境提供$ DISPLAY变量?

解决方案:

我实际上需要将export DISPLAY=:0.0放在echo中,以便在at启动环境后设置它。

line = echo "export DISPLAY=:0.0; python..." | at...
subprocess.Popen(line,Shell=True)

1 个答案:

答案 0 :(得分:0)

您需要通过获取当前环境,添加DISPLAY设置并将新环境传递给Popen创建的子shell,在python脚本中设置DISPLAY

import os;
new_env = dict(os.environ)
new_env['DISPLAY'] = '0.0'
...
...
subprocess.Popen(line, env=new_env, Shell=True)