How do I execute a command in a Python script?
In my Python script, I am trying to execute the following code:
import subprocess
subprocecss.call("xrdb -load ~/.XDefaults")
but it crashes with "No such file or directory" error, although it works when I paste the same code into the terminal. I also tried os.system (...) with os import, I tried it with "xrdb -merge ~ / .XDefaults", I tried to remove the ~ / from command, I even tried to change "to" no, no path . What am I doing wrong?
source to share
You need to use shell=True
or add a full path file:
subprocecss.call("xrdb -load ~/.XDefaults",shell=True)
from the python wiki :
On Unix with shell = True, the shell defaults to / bin / sh. If args is a string, the string specifies the command to be executed through the shell
On Windows with shell = True, the COMSPEC environment variable specifies the default shell. The only time you need to specify shell = True on Windows is when the command you want to execute is built into the shell (like dir or copy).
source to share
Note that since it subprocess.call
doesn't inherit from your environment by default, the value of ~ is undefined, so you either need to pass a flag shell=True
(potentially dangerous) or give an absolute path to type ~/.XDefaults
or use os.path.expanduser('~/.XDefaults')
to get it (as suggested by falstru).
source to share