예제 #1
0
def set_desktop_background(file):
    se = app('System Events')
    desktops = se.desktops.display_name.get()
    app('Finder').desktop_picture.set(mactypes.File(file))
    for d in desktops:
        desk = se.desktops[d]
        desk.picture.set(mactypes.File(file))
    subprocess.check_call("killall Dock", shell=True)
예제 #2
0
def change_background(path):
    """
        path = '/Users/zaijunwang/Pictures/screen/BulgariaPerseids.jpg'
    :param path:
    :return:
    """
    app('Finder').desktop_picture.set(mactypes.File(path))
예제 #3
0
def set_wallpaper(picpath):
    if sys.platform == 'win32':
        import win32api, win32con, win32gui
        k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER,
                                'Control Panel\Desktop', 0,
                                win32con.KEY_ALL_ACCESS)
        curpath = win32api.RegQueryValueEx(k, 'Wallpaper')[0]
        if curpath == picpath:
            pass
        else:
            # win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2")#2 for tile,0 for center
            # win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
            win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,
                                          picpath, 1 + 2)
        win32api.RegCloseKey(k)
    elif sys.platform == 'darwin':
        from appscript import app, mactypes, its
        se = app('System Events')
        desktops = se.desktops.display_name.get()
        # change wallpaper on all monitors
        for d in desktops:
            desk = se.desktops[its.display_name == d]
            desk.picture.set(mactypes.File(picpath))
    else:
        curpath = commands.getstatusoutput(
            'gsettings get org.gnome.desktop.background picture-uri')[1][1:-1]
        if curpath == picpath:
            pass
        else:
            commands.getstatusoutput(
                'DISPLAY=:0 gsettings set org.gnome.desktop.background picture-uri "%s"'
                % (picpath))
예제 #4
0
def change_desktops(default_file=None):
    se = app('System Events')
    desktops = se.desktops.display_name.get()
    f = default_file if default_file is not None else './calendar.jpg'
    for d in desktops:
        desk = se.desktops[its.display_name == d]
        desk.picture.set(mactypes.File(f))
예제 #5
0
def desktop_random():
	global curr_bg
	
	bg = random.choice(backgrounds)
	while bg == curr_bg:
		bg = random.choice(backgrounds)
	curr_bg = bg
	app('Finder').desktop_picture.set(mactypes.File(background_dir + bg))
예제 #6
0
def set_new(export_name,wallpaper_txt):
    
    new_wallpaper = open(wallpaper_txt, "w+")

    new_wallpaper.write(export_name)
    app('Finder').desktop_picture.set(mactypes.File(export_name))
    print("")
    return print("* New wallpaper has been set")
예제 #7
0
def update_background(local_path, test=False):
    """
    Update the System Background

    Parameters
    ----------
    local_path : str
        The local save location of the image
        :param test:
    """
    local_path = abspath(local_path)
    # print(local_path)
    assert isinstance(local_path, str)
    # print("Updating Background...", end='', flush=True)
    this_system = system()

    try:
        if this_system == "Windows":
            import ctypes
            SPI_SETDESKWALLPAPER = 0x14  #which command (20)
            SPIF_UPDATEINIFILE = 0x2  #forces instant update
            ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0,
                                                       local_path,
                                                       SPIF_UPDATEINIFILE)
            # for ii in np.arange(100):
            #     ctypes.windll.user32.SystemParametersInfoW(19, 0, 'Fit', SPIF_UPDATEINIFILE)
        elif this_system == "Darwin":
            from appscript import app, mactypes
            try:
                app('Finder').desktop_picture.set(mactypes.File(local_path))
            except Exception as e:
                if test:
                    pass
                else:
                    raise e

        elif this_system == "Linux":
            import os
            os.system(
                "/usr/bin/gsettings set org.gnome.desktop.background picture-options 'scaled'"
            )
            os.system(
                "/usr/bin/gsettings set org.gnome.desktop.background primary-color 'black'"
            )
            os.system(
                "/usr/bin/gsettings set org.gnome.desktop.background picture-uri {}"
                .format(local_path))
        else:
            raise OSError("Operating System Not Supported")
        # print("Success")
    except Exception as e:
        print("Failed")
        raise e
    #
    # if self.params.is_debug():
    #     self.plot_stats()

    return 0
예제 #8
0
def change_osx_background(filename):
    from appscript import app, mactypes  # use applescript modules

    se = app('System Events')  # fetch system events
    desktops = se.desktops.display_name.get()  # get all available displays
    for d in desktops:
        desk = se.desktops[d]
        # set wallpaper for each display
        desk.picture.set(mactypes.File(filename))
예제 #9
0
파일: mac.py 프로젝트: TehRawrz/wpchanger
def set_wallpaper(image_file_with_path):

    filepath = os.path.abspath(image_file_with_path)

    try:
        app('Finder').desktop_picture.set(mactypes.File(filepath))
        return True

    except Exception:
        return False
예제 #10
0
    def _set_wallpaper_mac(self, path):
        try:
            from appscript import app, mactypes
            app("Finder").desktop_picture.set(mactypes.File(path))
        except ImportError:
            script = """/usr/bin/osascript<<END
			tell application "Finder" to
			set desktop picture to POSIX file "%s"
			end tell
			END"""
            subprocess.Popen(script % path, shell=True)
예제 #11
0
def displayWallpaper(wallpaperPath):
    path, dirs, files = os.walk(wallpaperPath).__next__()
    fileName = wallpaperPath + random.choice(files)

    ## This works for ONE desktop
    try:
        from appscript import app, mactypes
        finder = app('Finder')
        finder.desktop_picture.set(mactypes.File(fileName))
    except:
        print("unable to update wallpaper")
예제 #12
0
def setNew(export_name, wallpaper_txt):

    new_wallpaper = open(wallpaper_txt, "w+")

    if os.path.isfile(wallpaper_txt):
        new_wallpaper.write(export_name)
        time.sleep(2)
        app('Finder').desktop_picture.set(mactypes.File(export_name))
    else:
        print("")
        print("* An error occured in setNew function")
        sys.exit()
    def update_MacOs_wallpaper(wallpaper_file: str) -> None:
        # app('Finder').desktop_picture.set(mactypes.File(f'{DOWNLOAD_FOLDER}/{new_file_name}.jpg'))

        # parser = argparse.ArgumentParser(description='Set desktop wallpaper.')
        # parser.add_argument('file', type=wallpaper_file, help='File to use as wallpaper.')
        # args = parser.parse_args()
        # f = args.file
        se = app('System Events')
        desktops = se.desktops.display_name.get()
        for d in desktops:
            desk = se.desktops[its.display_name == d]
            desk.picture.set(mactypes.File(wallpaper_file))

        return
예제 #14
0
def main(argv):
    success = False
    try:
        logging.info('reading wallpaper index page')
        page = read_url(WALLPAPER_INDEX_URL)
        uri = WALLPAPER_URI_PATTERN.findall(page)[0]
        url = WALLPAPER_URL_BASE + uri
        filename = os.path.basename(uri)
        logging.debug('wallpaper filename "%s"', filename)
        path = os.path.join(WALLPAPER_CACHE, filename)
        if not os.path.exists(path):
            logging.debug('wallpaper not exists')
            logging.info('reading wallpaper image data')
            data = read_url(url)
            logging.debug('checking wallpaper image data')
            file_obj = StringIO(data)
            image = Image.open(file_obj)
            image.load()
            logging.info('writing wallpaper image data')
            write_file(path, data)
        else:
            logging.debug('wallpaper exists')
        logging.info('changing wallpaper')
        app('Finder').desktop_picture.set(mactypes.File(path))
        success = True
        logging.info('all done')
    except IOError:
        logging.warn('network problem')
    except IndexError:
        logging.warn('wallpaper not found')
    if not success:
        filenames = os.listdir(WALLPAPER_CACHE)
        filename = random.choice(filenames)
        path = os.path.join(WALLPAPER_CACHE, filename)
        logging.info('changing wallpaper from cache')
        app('Finder').desktop_picture.set(mactypes.File(path))
        logging.info('all done')
예제 #15
0
def change_background(image_path: str):
    os = platform.system().lower()
    print(f'Setting background {image_path}')
    try:
        if 'darwin' in os:  # macOS
            from appscript import app, mactypes  # load only for macOS

            app('Finder').desktop_picture.set(mactypes.File(image_path))
        elif 'linux' in os:  # linux
            command = f"gsettings set org.gnome.desktop.background picture-uri '{image_path}'"
            subprocess.Popen(["/bin/bash", "-c", command])
        else:
            ctypes.windll.user32.SystemParametersInfoW(20, 0, image_path, 3)
    except Exception as e:
        print(f'Failed to set background at path {image_path}\n', e)
예제 #16
0
def ChangeDesktop():
    sp = spotipy.Spotify(auth=token)
    results = sp.current_user_playing_track()
    print(results['item']['album']['images'][1]['url'])
    url = results['item']['album']['images'][1]['url']

    file = 'current_artwork' + str(datetime.now()) + '.jpg'

    with open(file, 'wb') as f:
        f.write(requests.get(url).content)
        f.close()

    app('Finder').desktop_picture.set(mactypes.File(file))
    timepass.sleep(2)
    os.remove(file)
예제 #17
0
def animate(folder):
    l = list()
    a = list()
    for filename in os.listdir(folder):
        path = (os.path.join(folder, filename))
        if path.endswith('jpg'):
            l.append(path)
    f = sorted(l)
    f = list(dict.fromkeys(f))
    f.sort(key=natural_keys)

    while True:
        for ele in f:
            print(ele)
            app('Finder').desktop_picture.set(mactypes.File(ele))
            time.sleep(.001)
예제 #18
0
    def put(self, vfsFile, overwrite, LUID=None):
        rid = FileDataProvider.FolderTwoWay.put(self, vfsFile, True, LUID)

        #if the file was successfully transferred then set it
        #as the wallpaper
        if vfsFile.exists():
            if WPTYPE == WPMAC:
                print "SETTING BACKGROUND IMAGE"
                app('Finder').desktop_picture.set(
                    mactypes.File(vfsFile.get_local_uri()))
            else:
                self._client.set_string(
                    "/desktop/gnome/background/picture_filename",
                    vfsFile.get_local_uri())

        return rid
예제 #19
0
def _set_wallpaper_mac(path):
    """Set wallpaper for mac desktop environment

	Source:
	http://stackoverflow.com/questions/1977694/change-desktop-background/21213504#21213504

	"""
    try:
        app("Finder").desktop_picture.set(mactypes.File(path))
    except ImportError:
        script = """/usr/bin/osascript<<END
		tell application "Finder" to
		set desktop picture to POSIX file "%s"
		end tell
		END"""
        subprocess.Popen(script % path, shell=True)
예제 #20
0
def change_mac_background(file_path):
    """
    Change the background on Mac operating systems
    """
    try:
        from appscript import app, mactypes
        app('Finder').desktop_picture.set(mactypes.File(file_path))
    except ImportError:
        import subprocess
        SCRIPT = """
                 /usr/bin/osascript<<END
                 tell application "Finder" to
                 set desktop picture to POSIX file "%s"
                 end tell
                 END
                 """
        subprocess.Popen(SCRIPT % file_path, shell=True)
예제 #21
0
def set_new_wallpaper(image_name, current_wallpaper):
    new_wallpaper = open(current_wallpaper, "w+")
    new_wallpaper.write(image_name)
    if HOST_OS == 'Darwin':
        # Apple
        from appscript import app, mactypes
        app('Finder').desktop_picture.set(mactypes.File(os.path.join(ROOT_DIR, image_name)))
    elif HOST_OS == 'Windows':
        # Windows
        import ctypes
        ctypes.windll.user32.SystemParametersInfoW(20, 0, os.path.join(ROOT_DIR, image_name) , 3)
    else:
        error_handler("Unsupported OS")

    new_wallpaper.close()
    print("")
    print(TermStyle.BOLD + TermStyle.OKGREEN + f"[+] New Wallpaper Set - {image_name}" + TermStyle.ENDC)
예제 #22
0
def change_background_image():
    """Changes desktop background to NASA POD pulled from API

	Arguments: None
	
	Usage: Currently only works on Macs. Ensure a valid API key is added.
	"""

    #Calculate current date and yesterday's date
    now = datetime.now()
    month = str(now.month)
    day = str(now.day)
    if (now.month < 10):
        month = '0' + str(now.month)
    if (now.day < 10):
        day = '0' + str(now.day)
    year = str(now.year)
    timestamp = month + day + year

    yesterday = datetime.now() - timedelta(days=1)
    yesterday_month = str(yesterday.month)
    yesterday_day = str(yesterday.day)
    if (yesterday.month < 10):
        yesterday_month = '0' + str(yesterday.month)
    if (yesterday.day < 10):
        yesterday_day = '0' + str(yesterday.day)
    yesterday_year = str(yesterday.year)
    yesterday_timestamp = yesterday_month + yesterday_day + yesterday_year

    path = os.path.dirname(os.path.realpath(__file__))

    #Pull image url from NASA POD API
    api_response = requests.get(
        'https://api.nasa.gov/planetary/apod?api_key=' + API_KEY)
    link = api_response.json()['hdurl']
    urllib.request.urlretrieve(link, path + '/' + timestamp + '.jpg')

    #Change desktop background to NASA image and remove previous image
    app('Finder').desktop_picture.set(
        mactypes.File(path + '/' + timestamp + '.jpg'))

    try:
        os.remove(path + yesterday_timestamp + '.jpg')
    except:
        pass
def main():

    print(len(sys.argv))  # Debug the arg by output to terminal

    # Build the "today" URL variable
    url = "https://www.gocomics.com/calvinandhobbesespanol/"
    if len(sys.argv) < 2:
        today = datetime.datetime.now()
        url += today.strftime("%Y/%m/%d/")
    else:
        url += sys.argv[1]
        if url[-1] != "/":
            url += "/"

    print(url)  # Debug the string by output to terminal

    # Request URL, Open it, Read in data
    req = urllib.request.Request(url)
    resp = urllib.request.urlopen(req)
    respData = resp.read()

    # Regex to find the comic graphic asset
    if re.search(r"https://assets\.amuniversal[^\"]*", str(respData)):
        comic = re.findall(r"https://assets\.amuniversal[^\"]*",
                           str(respData))[0]
    else:
        return 1

    print(comic)  # Debug the string of the comic found

    # Grab asset and write to workstation
    try:
        os.remove("/tmp/liveComic.png")
    except OSError:
        pass

    urlretrieve(comic, "/tmp/liveComic.png")

    # Set wallpaper
    app("Finder").desktop_picture.set(mactypes.File("/tmp/liveComic.png"))

    return 0
예제 #24
0
def set_wallpaper_image(path):
    """
    sets the desktop wallpaper

    returns True on success
            False on failure
    """

    try:
        if sys.platform == 'win32':
            import ctypes

            ctypes.windll.user32.SystemParametersInfoW(20, 0, path, 0)
        else:
            from appscript import app, mactypes

            app('Finder').desktop_picture.set(mactypes.File(path))
    except:
        return False

    return True
예제 #25
0
파일: sunback.py 프로젝트: t-rad679/sunback
    def update_background(local_path):
        """
        Update the System Background

        Parameters
        ----------
        local_path : str
            The local save location of the image
        """
        print("Updating Background...", end='', flush=True)
        assert isinstance(local_path, str)

        import platform
        this_system = platform.system()

        try:
            if this_system == "Windows":
                import ctypes
                ctypes.windll.user32.SystemParametersInfoW(20, 0, local_path, 0)
            elif this_system == "Darwin":
                from appscript import app, mactypes
                app('Finder').desktop_picture.set(mactypes.File(local_path))
            elif this_system == "Linux":
                import os
                os.system(
                    "/usr/bin/gsettings set org.gnome.desktop.background picture-uri {}".format(local_path))
            else:
                raise OSError("Operating System Not Supported")




            print("Success")
        except:
            print("Failed")
            raise
        return 0
def change_desktop_wallpaper(imageAddress):
    app('Finder').desktop_picture.set(mactypes.File(imageAddress))
    os.system("Killall Dock")
예제 #27
0
def set_wallpaper(image):

    desktop_env = get_desktop_environment()

    if desktop_env in ['gnome', 'unity', 'cinnamon', 'pantheon']:

        uri = 'file://%s' % image

        try:

            SCHEMA = 'org.gnome.desktop.background'
            KEY = 'picture-uri'
            gsettings = Gio.Settings.new(SCHEMA)

            gsettings.set_string(KEY, uri)

        except:

            args = [
                'gsettings', 'set', 'org.gnome.desktop.background',
                'picture-uri', uri
            ]
            subprocess.Popen(args)

    elif desktop_env == 'mate':

        try:  # MATE >= 1.6

            args = [
                'gsettings', 'set', 'org.mate.background', 'picture-filename',
                '%s' % image
            ]
            subprocess.Popen(args)

        except:  # MATE < 1.6

            args = [
                'mateconftool-2', '-t', 'string', '--set',
                '/desktop/mate/background/picture_filename',
                '%s' % image
            ]
            subprocess.Popen(args)

    elif desktop_env == 'gnome2':

        args = [
            'gconftool-2', '-t', 'string', '--set',
            '/desktop/gnome/background/picture_filename',
            '%s' % image
        ]
        subprocess.Popen(args)

    elif desktop_env == 'kde':

        kde_script = dedent('''\
		var Desktops = desktops();
		for (i=0;i<Desktops.length;i++) {{
			d = Desktops[i];
			d.wallpaperPlugin = "org.kde.image";
			d.currentConfigGroup = Array("Wallpaper",
										"org.kde.image",
										"General");
			d.writeConfig("Image", "file://{}")
		}}
		''').format(image)

        subprocess.Popen([
            'dbus-send', '--session', '--dest=org.kde.plasmashell',
            '--type=method_call', '/PlasmaShell',
            'org.kde.PlasmaShell.evaluateScript',
            'string:{}'.format(kde_script)
        ])

    elif desktop_env in ['kde3', 'trinity']:

        args = 'dcop kdesktop KBackgroundIface setWallpaper 0 "%s" 6' % image
        subprocess.Popen(args, shell=True)

    elif desktop_env == 'xfce4':

        # XFCE4's image property is not image-path but last-image (What?)
        # Only GNOME seems to have a sane wallpaper interface

        # Update: the monitor id thing seems to be changed in
        # XFCE 4.12 to just monitor0 instead of monitorVGA1 or something
        # So now we need to do both.

        list_of_properties_cmd = subprocess.Popen(
            ['bash -c "xfconf-query -R -l -c xfce4-desktop -p /backdrop"'],
            shell=True,
            stdout=subprocess.PIPE)

        list_of_properties, list_of_properties_err = list_of_properties_cmd.communicate(
        )

        list_of_properties = list_of_properties.decode('utf-8')

        for i in list_of_properties.split('\n'):

            if i.endswith('last-image'):

                # The property given is a background property
                subprocess.Popen([
                    'xfconf-query -c xfce4-desktop -p %s -s "%s"' % (i, image)
                ],
                                 shell=True)

                subprocess.Popen(['xfdesktop --reload'], shell=True)

    elif desktop_env == 'razor-qt':

        desktop_conf = configparser.ConfigParser()
        # Development version

        desktop_conf_file = os.path.join(get_config_dir('razor'),
                                         'desktop.conf')

        if os.path.isfile(desktop_conf_file):

            config_option = r'screens\1\desktops\1\wallpaper'

        else:

            desktop_conf_file = os.path.join(os.path.expanduser('~'),
                                             '.razor/desktop.conf')
            config_option = r'desktops\1\wallpaper'

        desktop_conf.read(os.path.join(desktop_conf_file))

        try:

            if desktop_conf.has_option(
                    'razor', config_option):  # only replacing a value

                desktop_conf.set('razor', config_option, image)

                with codecs.open(desktop_conf_file,
                                 'w',
                                 encoding='utf-8',
                                 errors='replace') as f:

                    desktop_conf.write(f)

        except:
            pass

    elif desktop_env in ['fluxbox', 'jwm', 'openbox', 'afterstep', 'i3']:

        try:

            args = ['feh', '--bg-scale', image]
            subprocess.Popen(args)

        except:

            sys.stderr.write('Error: Failed to set wallpaper with feh!')
            sys.stderr.write('Please make sre that You have feh installed.')

    elif desktop_env == 'icewm':

        args = ['icewmbg', image]
        subprocess.Popen(args)

    elif desktop_env == 'blackbox':

        args = ['bsetbg', '-full', image]
        subprocess.Popen(args)

    elif desktop_env == 'lxde':

        args = 'pcmanfm --set-wallpaper %s --wallpaper-mode=scaled' % image
        subprocess.Popen(args, shell=True)

    elif desktop_env == 'lxqt':

        args = 'pcmanfm-qt --set-wallpaper %s --wallpaper-mode=scaled' % image
        subprocess.Popen(args, shell=True)

    elif desktop_env == 'windowmaker':

        args = 'wmsetbg -s -u %s' % image
        subprocess.Popen(args, shell=True)

    elif desktop_env == 'enlightenment':

        args = 'enlightenment_remote -desktop-bg-add 0 0 0 0 %s' % image
        subprocess.Popen(args, shell=True)

    elif desktop_env == 'awesome':

        with subprocess.Popen("awesome-client",
                              stdin=subprocess.PIPE) as awesome_client:

            command = 'local gears = require("gears"); for s = 1, screen.count() do gears.wallpaper.maximized("%s", s, true); end;' % image
            awesome_client.communicate(input=bytes(command, 'UTF-8'))

    elif desktop_env == 'windows':

        WIN_SCRIPT = '''reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v Wallpaper /t REG_SZ /d  %s /f

rundll32.exe user32.dll,UpdatePerUserSystemParameters
''' % image

        win_script_file = open(
            os.path.abspath(os.path.expanduser('~/.weatherdesk_script.bat')),
            'w')

        win_script_file.write(WIN_SCRIPT)

        win_script_file.close()

        subprocess.Popen(
            [os.path.abspath(os.path.expanduser('~/.weatherdesk_script.bat'))],
            shell=True)

    elif desktop_env == 'mac':

        try:

            from appscript import app, mactypes

            app('Finder').desktop_picture.set(mactypes.File(image))

        except ImportError:

            OSX_SCRIPT = '''tell application "System Events"
								  set desktopCount to count of desktops
									repeat with desktopNumber from 1 to desktopCount
									  tell desktop desktopNumber
										set picture to POSIX file "%s"
									  end tell
									end repeat
								end tell
			''' % image

            osx_script_file = open(
                os.path.expanduser('~/.weatherdesk_script.AppleScript'), 'w')

            osx_script_file.truncate()

            osx_script_file = open(
                os.path.expanduser('~/.weatherdesk_script.AppleScript'), 'w')

            osx_script_file.truncate()

            osx_script_file.write(OSX_SCRIPT)

            osx_script_file.close()

            subprocess.Popen([
                '/usr/bin/osascript',
                os.path.abspath(
                    os.path.expanduser('~/.weatherdesk_script.AppleScript'))
            ])
    else:

        sys.stderr.write(
            'Error: Failed to set wallpaper. (Desktop not supported)')

        return False

    return True
예제 #28
0
 def change_desktop_background(self):
     while(True):
         path = f'{self.sysRoot}/Desktop/background.jpg'
         # Access mac for funcionality eg, changing dekstop wallpaper
         app('Finder').desktop_picture.set(mactypes.File(path))
         time.sleep(10)
예제 #29
0
# -*- coding: utf-8 -*-
from appscript import app, mactypes

app('Finder').desktop_picture.set(
    mactypes.File('/Users/gaoqiang/Desktop/boom/1.jpg'))
예제 #30
0
def changeWallpaper(filename):
	app('Finder').desktop_picture.set(mactypes.File(filename))