如何在Bash中使用$DISPLAY?
我正在开发一个Python的图形界面应用程序,有时候我需要推迟执行一些大的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.
问题:
- 是什么原因导致这个错误出现的?
- 我该如何将$DISPLAY变量提供给
at
的环境?
解决方案:
其实我需要把export DISPLAY=:0.0
放在echo里面,这样它才能在at
启动它的环境后被设置。
line = echo "export DISPLAY=:0.0; python..." | at...
subprocess.Popen(line,Shell=True)
1 个回答
2
你需要在Python脚本中设置DISPLAY
。具体来说,就是获取当前的环境,然后添加DISPLAY
的设置,最后把这个新的环境传递给Popen创建的子进程。
import os;
new_env = dict(os.environ)
new_env['DISPLAY'] = '0.0'
...
...
subprocess.Popen(line, env=new_env, Shell=True)