Reputation: 21
This code randomly selects a picture in a "Picture" folder and changes the desktop background to that picture. When I run the code in the IDE, it works. When I run it in terminal, it doesn't work. I placed print statements in there to see what it was doing, and it looks like it is not grabbing the full file path when I run it from the terminal. I want the ability to run this program from the terminal. Any thoughts?
import ctypes
import os
import sys
from random import randrange
x = randrange(3)
pathname = os.path.dirname(sys.argv[0])
pathname.replace("change_background.py", "")
pathname = pathname + "/Pictures/"
def change_pic(image_name):
pathToJpg = os.path.normpath("{}{}".format(pathname, image_name))
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, pathToJpg, 0)
if x == 0:
change_pic("image1.jpg")
if x == 1:
change_pic("image2.jpg")
if x == 2:
change_pic("image3.jpg")
Upvotes: 0
Views: 1039
Reputation: 21
Here is the updated code. os.getcwd() worked a lot better.
import ctypes
import os
from random import randrange
dir_name = "Pictures"
pathname = os.getcwd()
pathname_pic = pathname + "/{}".format(dir_name)
if not os.path.exists(pathname_pic):
os.mkdir(pathname_pic)
print("Created directory called \"{}\". Place pictures inside new directory".format(dir_name))
files_in_dir = []
# r=>root, d=>directories, f=>files
# this grabs all of the images in the directory
for r, d, f in os.walk(pathname_pic):
for item in f:
if '.jpg' in item:
files_in_dir.append(os.path.join(r, item))
if '.png' in item:
files_in_dir.append(os.path.join(r, item))
def change_pic():
if len(files_in_dir) == 0:
print("You don't have any pictures in your directory")
else:
x = randrange(len(files_in_dir))
print("Picture chosen: {}".format(files_in_dir[x]))
pathToJpg = files_in_dir[x]
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, pathToJpg, 0)
x = x - 1
if __name__ == "__main__":
change_pic()
Upvotes: 1
Reputation: 83527
Your IDE basically executes a command in a command line. You should see if the IDE prints out the exact command it runs so you can understand what is going on here. Most likely it is something like python /home/my_user/my_code/my_program.py
, so when you do pathname = os.path.dirname(sys.argv[0])
, your python code parses the path from the command-line.
Now when you run from the command line, you probably do something like python my_program.py
instead, so the code behaves differently because there is different input. If you type the exact same command that the IDE runs, then you will get the exact same output.
As your self-answer shows, a better solution is to write the code in such a way that it doesn't rely on this difference in how the program is run and still provides the same result.
Upvotes: 0