Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute command in Python script? [duplicate]

In my Python script I'm trying to execute next code:

import subprocess
subprocecss.call("xrdb -load ~/.XDefaults")

but it falls with error: "No such file or directory", although it works when I paste the same code to terminal. I also tryed os.system(...) with import os, I tried it with "xrdb -merge ~/.XDefaults", I tried to delete ~/ from command, I even tried to change "" to '', no way. What I'm doing wrong?

like image 284
banan-olivka Avatar asked Apr 09 '26 16:04

banan-olivka


2 Answers

You need to use shell=True or add your file with full path :

subprocecss.call("xrdb -load ~/.XDefaults",shell=True)

from python wiki :

On Unix with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute 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 wish to execute is built into the shell (e.g. dir or copy).

like image 120
Mazdak Avatar answered Apr 12 '26 04:04

Mazdak


Note that since subprocess.call by default doesn't inherit your environment the value for ~ is not defined so you either need to pass the shell=True flag, (potentially dangerous), or give the absolute path for ~/.XDefaults by typing it in or using os.path.expanduser('~/.XDefaults') to get it, (as suggested by falstru).

like image 32
Steve Barnes Avatar answered Apr 12 '26 06:04

Steve Barnes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!