Python,隐藏目录的异常行为

时间:2016-11-20 19:34:44

标签: python python-2.7

我写了一个python脚本来从bing.com设置我的Ubuntu-gnome桌面壁纸。

#!/usr/bin/python
import urllib
import urllib2
import os
from bs4 import BeautifulSoup

imageurl='http://www.bing.com'
page=urllib2.urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-IN/')
xml=page.read()
soup=BeautifulSoup(xml,'xml')
imageurl += soup.url.string
imageurl=imageurl[:-12]+'1920x1080.jpg'
print imageurl
try:
    urllib.urlretrieve(imageurl, "wallpaper1.jpg")
    if os.path.isfile('wallpaper.jpg'):
        os.remove('wallpaper.jpg')
    os.rename('wallpaper1.jpg','wallpaper.jpg')
except Exception as e:
    pass
os.system("gsettings set org.gnome.desktop.background picture-uri file:///home/sumit/.myscripts/wallpaper.jpg")

当我从正常目录运行它时,我的脚本工作得非常好,但是当我将它复制到隐藏目录(/home/sumit/.myscripts)后使用相同的脚本时,它给出了错误:

Traceback (most recent call last):
  File "/home/sumit/.myscripts/bing.py", line 18, in <module>
    os.rename('/home/sumit/.myscripts/wallpaper1.jpg','/home/sumit/.myscripts/wallpaper.jpg')
OSError: [Errno 2] No such file or directory

图片没有下载。但是当我用绝对路径替换每个地方的路径时,它才有效。

#!/usr/bin/python
import urllib
import urllib2
import os
from bs4 import BeautifulSoup

imageurl='http://www.bing.com'
page=urllib2.urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-IN/')
xml=page.read()
soup=BeautifulSoup(xml,'xml')
imageurl += soup.url.string
imageurl=imageurl[:-12]+'1920x1080.jpg'
print imageurl
try:
    urllib.urlretrieve(imageurl, "/home/sumit/.myscripts/wallpaper1.jpg")
    if os.path.isfile('/home/sumit/.myscripts/wallpaper.jpg'):
        os.remove('/home/sumit/.myscripts/wallpaper.jpg')
    os.rename('/home/sumit/.myscripts/wallpaper1.jpg','/home/sumit/.myscripts/wallpaper.jpg')
except Exception as e:
    print 'Unable to download'
os.system("gsettings set org.gnome.desktop.background picture-uri file:///home/sumit/.myscripts/wallpaper.jpg")

我对这种行为感到困惑。如果有人可以解释我正在进行的事情,那将是非常有帮助的,因为我是python的新手。

0 个答案:

没有答案