Python程序表现不一致

今天写一个小Python玩具的时候碰到了一个奇怪的问题

环境

  • Ubuntu 16.04
  • Python3

问题

  • 如果手动运行这个程序,一切正常
  • 如果是开机下启动的话,程序运行后能够正常从Bing获取图片,但是壁纸并不会被修改,终端运行gsettings 查看壁纸的路径是默认路径

源代码

这段代码的主要功能是上Bing抓一张背景图片,保存到本地,并且设置这张图片为壁纸

  • 为了不用每天都手动运行这个程序,开头setup部分将这个py文件添加到了~/.profile(准确来说应该是登陆启动)
  • 中间(web resource getter)是抓取的代码,考虑到开机没有联网的情况,用while循环在外面裹了一下
  • 接着(wall paper switcher)是设置壁纸的代码
  • 最后是让线程睡到明天12点
#!/usr/bin/python3

import urllib.request
import urllib.error
import re
import os
import time
import datetime


def log(string):
    logPath = os.path.abspath(os.path.dirname(__file__)) + '/log'
    with open(logPath, 'a') as log:
        log.write(string + '\n')

# wallpaper absolute path
wallPaperPath = os.path.abspath(os.path.dirname(__file__)) + '/wallpaper.jpg'

# simple setup
# automatically run when login
# warning: make sure there's a wallpaper.jpg after running this program for the first time
# warning: otherwise it may continue to add command into ~/.profile
if not os.path.exists(wallPaperPath):
    log('[SETUP]: ' + 'echo "' + os.path.abspath(__file__) + ' &" >>  ~/.profile')
    os.system('echo "' + os.path.abspath(__file__) + ' &" >>  ~/.profile')

# run
while True:
    # web resource getter
    while True:
        try:
            # open www.bing.com(actually http://www.bing.com/?mkt=zh-CN)
            with urllib.request.urlopen('http://www.bing.com/') as response:
                page = response.read().decode('utf-8')
            # extract the URL of wall paper
            urlPrefix = 'http://www.bing.com'
            patternString = 'g_img={url: "(.*?)"'
            pattern = re.compile(patternString)
            result = pattern.findall(page)
            wallPaperURL = urlPrefix + result[0]
            # get the wall paper
            with urllib.request.urlopen(wallPaperURL) as response:
                with open(wallPaperPath, "wb") as file:
                    file.write(response.read())
            log('[ RUN ]: Download Picture Done')
            break  # exist the loop
        # when cannot connect to the internet
        except urllib.error.URLError as urlError:
            time.sleep(20)  # wait 20 seconds
            log('[ERROR]: URLError')
            continue  # continue the loop
        # other errors
        except Exception as e:
            time.sleep(20)  # wait 20 seconds
            log('[ERROR]: Exception')
            continue  # continue the loop
    
    # wall paper switcher
    # test  current wallpaper
    sysWallpaper = os.popen('gsettings get org.gnome.desktop.background picture-uri').read().strip()
    configWallpaper = '\'file://' + wallPaperPath + '\''
    # spare no effort to change the wallpaper :)
    while not sysWallpaper == configWallpaper:
        # change wallpaper through command line
        os.system('gsettings set org.gnome.desktop.background picture-uri "file://' + wallPaperPath + '"')
        log('[ RUN ]: ' + 'gsettings set org.gnome.desktop.background picture-uri "file://' + wallPaperPath + '"')
        time.sleep(5)
        # test current wallpaper again
        sysWallpaper = os.popen('gsettings get org.gnome.desktop.background picture-uri').read().strip()
    log('[ RUN ]: Change Wallpaper Done')
    # set next run time
    # never tested
    tomorrow = datetime.datetime.replace(datetime.datetime.now() + datetime.timedelta(days=1), hour=0, minute=0, second=0)
    delta = tomorrow - datetime.datetime.now()
    time.sleep(delta.seconds)

一个月后的更新

问题出现了快一个月
感谢@任卫 的回答,我尝试按照该链接清除缓存,但是问题还是会出现。
但是当我将程序放在虚拟机上运行时,它运行的好好的。。。

当初写程序的时候考虑过写入cron.d里面,但是貌似需要权限,这么一个小玩具我觉得还是不需要权限比较好。
当然我没有仔细了解corn.d的详细情况,但是隐约记得可以为当前用户创建一个corn.d?(我已经不记得了)不过我发懒就直接while 每天了。

直到一个月后我再次打开Ubuntu的时候。。。问题解决了。我没有对.py/.profile做任何修改,但是它就是没问题了。。。

也许这就是玄学吧。。。

所以这个BUG现在我已经没办法复现了。。。不过还是希望有知道什么情况的朋友能给我科普下

阅读 2.5k
1 个回答

[[https://askubuntu.com/questio... gnome - Problem with setting wallpaper using gsettings - Ask Ubuntu]]
我不知道你看到这个问题么,意思是有缓存。

另外我建议不要while每天了,也不要写到.profile里, 写到cron.d里更好吧

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题