I found some code that should change my wallpaper:
import subprocess
SCRIPT = """/usr/bin/osascript<<END
tell application "Finder"
set desktop picture to POSIX file "%s"
end tell
END"""
def set_desktop_background(filename):
subprocess.Popen(SCRIPT%filename, shell=True)
set_desktop_background("image.png")
But I get this error:
30:45: execution error: Finder got an error: AppleEvent handler failed. (-10000)
Does anyone know what went wrong, or what I can do about this?
Your AppleScript is causing the error. Instead, try using the code from this answer. Note that you need to use an absolute path, so you should use os.path.abspath():
import subprocess
import os
SCRIPT = """/usr/bin/osascript<<END
tell application "System Events" to set picture of (reference to current desktop) to "%s"
END"""
def set_desktop_background(filename):
abspath = os.path.abspath(filename)
subprocess.Popen(SCRIPT % abspath, shell=True)
set_desktop_background("image.png")
Related
im using an email lookup module, called holehe (more can be found on it here - https://github.com/megadose/holehe) and i want to make it so when you enter an email it will automatically with in your python console output what came out from the new CMD window, makes it easier for my and colleges to use. How can i go about this? My code it bellow
import holehe
import os
from os import system
import subprocess
email = input("Email:")
p = subprocess.Popen(["start", "cmd", "/k", "holehe", email], shell = True)
p.wait()
input()
Thank you for answers
I'm trying to write a python script that can launch DaVinci Resolve in headless mode, then send it some commands via its API, then close it.
What I'm looking for would look something like
Open resolve.exe with argument --nogui
Do stuff with the API here
Terminate this instance of Resolve
I've managed to launch an instance of Resolve in headless. But it always ends up being a subprocess of something else. While it's running as a subprocess, I can't get the API to communicate with it.
Here's the code of tried
import subprocess
args = ["C:\Program Files\Blackmagic Design\DaVinci Resolve\Resolve.exe", '--nogui']
resolve_headles = subprocess.Popen(args)
from python_get_resolve import GetResolve
resolve = GetResolve()
This should return an object of Resolve, but it always fails.
I believe this is because its running as a subprocess of my IDE
I've also tried this
from subprocess import call
dir = "C:\Program Files\Blackmagic Design\DaVinci Resolve"
cmdline = "Resolve.exe --nogui"
rc = call("start cmd /K " + cmdline, cwd=dir, shell=True)
This just has the same problem of Resolve running as a subprocess of Windows Command Processor.
I am trying to create a script that will display a page in chrome on startup. That is, I am trying to run a python script on startup. I am using the winreg module to do so.
Here is my script to add a my page display script on startup:
import winreg
import os
import sys, traceback
def AddToRegistry():
pth = os.path.dirname(os.path.realpath(path_to_page_display_script))
s_name="test.py"
address=os.path.join(pth,s_name)
try:
open = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\\Microsoft\\Windows\\CurrentVersion\\Run", reserved=0, access = winreg.KEY_ALL_ACCESS)
winreg.SetValueEx(open,"pytest",0,winreg.REG_SZ,address)
winreg.CloseKey(open)
except Exception:
traceback.print_exc(file=sys.stdout)
if __name__=="__main__":
AddToRegistry()
Here is my page display script:
import webbrowser
url = 'http://docs.python.org/'
chrome_path = 'path_to_chrome/chrome.exe %s'
webbrowser.get(chrome_path).open(url)
The script runs fine without any errors but on restarting my machine, the chrome does not open up by itself nor does it display the page. Basically, my script does not run. What is wrong ? Kindly help me out.
The problem isn't with your script. It's with your registry key.
You need to tell windows to invoke Python.exe C:\path_to_script\test.py, not test.py.
So instead of this:
This:
path_to_python_exe = "C:\\python\\python38";
address=os.path.join(pth,s_name)
address = os.path.join(path_to_python_exe, "python.exe") + " " + address;
Or if Python.exe is guaranteed to be in your PATH, simply this:
address = "Python.exe" + " " + os.path.join(pth,s_name)
I'm writing a PyGTK GUI application in Ubuntu to browse some images, and I'd like to open an image in the default image viewer application when it is double-clicked (like when it is opened in Nautilus).
How can I do it?
I don't know specifically using PyGTK but: xdg-open opens the default app for a file so running something like this should work:
import os
os.system('xdg-open ./img.jpg')
EDIT: I'd suggest using the subprocess module as in the comments. I'm not sure exactly how to use it yet so I just used os.system in the example to show xdg-open.
In GNU/Linux use xdg-open, in Mac use open, in Windows use start. Also, use subprocess, if not you risk to block your application when you call the external app.
This is my implementation, hope it helps: http://goo.gl/xebnV
import sys
import subprocess
import webbrowser
def default_open(something_to_open):
"""
Open given file with default user program.
"""
# Check if URL
if something_to_open.startswith('http') or something_to_open.endswith('.html'):
webbrowser.open(something_to_open)
return 0
ret_code = 0
if sys.platform.startswith('linux'):
ret_code = subprocess.call(['xdg-open', something_to_open])
elif sys.platform.startswith('darwin'):
ret_code = subprocess.call(['open', something_to_open])
elif sys.platform.startswith('win'):
ret_code = subprocess.call(['start', something_to_open], shell=True)
return ret_code
GTK (>= 2.14) has gtk_show_uri:
gtk.show_uri(screen, uri, timestamp)
Example usage:
gtk.show_uri(None, "file:///etc/passwd", gtk.gdk.CURRENT_TIME)
Related
How to open a file with the standard application?
I use this bit of code in my script to pinpoint, in a cross-platform way, where exactly it's being run from:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
Pretty simple. I then go on to use SCRIPT_ROOT in other areas of my script to make sure everything is properly relative. My problem occurs when I run it through py2exe, because the generated executable doesn't set __file__, therefore my script breaks. Does anyone know how to fix or work around this?
Here is the py2exe documentation reference and here are the relevant items:
sys.executable is set to the full pathname of the exe-file.
The first item in sys.argv is the full pathname of the executable, the rest are the command line arguments.
sys.frozen only exists in the executable. It is set to "console_exe" for a console executable, to "windows_exe" for a console-less gui executable, and to "dll" for a inprocess dll server.
__file__ is not defined (you might want to use sys.argv[0] instead)
It is not apparent from those docs whether "the exe-file" and "the executable" are the same thing, and thus whether sys.executable and sys.argv[0] are the same thing. Looking at code that worked for both script.py and py2exe_executable.exe last time I had to do this, I find something like:
if hasattr(sys, 'frozen'):
basis = sys.executable
else:
basis = sys.argv[0]
required_folder = os.path.split(basis)[0]
As I say that worked, but I don't recall why I thought that was necessary instead of just using sys.argv[0].
Using only basis was adequate for the job in hand (read files in that directory). For a more permanent record, split something like os.path.realpath(basis).
Update Actually did a test; beats guesswork and armchair pontification :-)
Summary: Ignore sys.frozen, ignore sys.executable, go with sys.argv[0] unconditionally.
Evidence:
=== foo.py ===
# coding: ascii
import sys, os.path
print 'sys has frozen:', hasattr(sys, 'frozen')
print 'using sys.executable:', repr(os.path.dirname(os.path.realpath(sys.executable)))
print 'using sys.argv[0]:', repr(os.path.dirname(os.path.realpath(sys.argv[0] )))
=== setup.py ===
from distutils.core import setup
import py2exe
setup(console=['foo.py'])
=== results ===
C:\junk\so\py2exe>\python26\python foo.py
sys has frozen: False
using sys.executable: 'C:\\python26'
using sys.argv[0]: 'C:\\junk\\so\\py2exe' # where foo.py lives
C:\junk\so\py2exe>dist\foo
sys has frozen: True
using sys.executable: 'C:\\junk\\so\\py2exe\\dist'
using sys.argv[0]: 'C:\\junk\\so\\py2exe\\dist' # where foo.exe lives
Py2exe does not define __file__: http://www.py2exe.org/index.cgi/Py2exeEnvironment
The OP requested a py2exe friendly version of:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
The best answer is to determine if python is frozen in an exe, py2exe has documentation on this:
http://www.py2exe.org/index.cgi/HowToDetermineIfRunningFromExe
import imp, os, sys
def main_is_frozen():
return (hasattr(sys, "frozen") or # new py2exe
hasattr(sys, "importers") # old py2exe
or imp.is_frozen("__main__")) # tools/freeze
def get_main_dir():
if main_is_frozen():
return os.path.dirname(sys.executable)
return os.path.dirname(os.path.realpath(__file__))
SCRIPT_ROOT = get_main_dir()
Since, the python is EAFP, here's an EAFP version ...
try:
if sys.frozen or sys.importers:
SCRIPT_ROOT = os.path.dirname(sys.executable)
except AttributeError:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
Cheers!
sys.argv[0] is a reliable way to get the path, as it will give the same result irrespective of being run as a script or exe
. To get the directory os.path.dirname(sys.argv[0])
Try this:
import os
import sys
os.path.realpath(os.path.dirname(sys.argv[0]))