1

I can run:

sudo service postgresql start

from the command line with no issues. However when I try running the following:

import os
from subprocess import Popen,PIPE

pwd = getsudopwd()
cmd = ['sudo','service',process,'state']
p = Popen(cmd,stdout=PIPE,stdin=PIPE,stderr=PIPE,universal_newlines=True)
out,err = p.communicate(pwd+'\n')
if err: raise RuntimeError(err)

I get the following error

chmod: changing permissions of '/var/run/postgresql': Operation not permitted. So, why is there is an error accessing the pid directory for postgresql when this is run from Python?

WraithWireless
  • 634
  • 9
  • 21

3 Answers3

2

You can simply use -S with sudo:

from subprocess import Popen, PIPE
import getpass

pwd = getpass.getpass()
proc = Popen(['sudo', '-S', 'service',process,'state'],
             stdout=PIPE, stdin=PIPE, stderr=PIPE,universal_newlines=True)
out,err= proc.communicate(input="{}\n".format(pwd))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • 1
    you should leave `stdout`, `stderr` separate: `stderr=PIPE` as in the question (`sudo` writes the prompt to stderr with the `--stdin` option, the child process might right to stdout something useful). – jfs Feb 22 '15 at 01:38
0

i suggest you use the sh library

its very simple and easy to use

from sh import sudo
print sudo('service postgresql start')
Urban48
  • 1,398
  • 1
  • 13
  • 26
0

Running sudo command with the -S option and piping your password to the stdin of the sudo command should solve your problem.

import os
from subprocess import Popen, PIPE

echo = Popen(('echo', 'mypasswd'), stdout = PIPE)
p = Popen(['sudo', '-S', 'service', 'postgresql', 'restart'], stdin = echo.stdout, stdout = PIPE, stderr = PIPE, universal_newlines = True)
out, err = p.communicate()
print out
Boris
  • 2,275
  • 20
  • 21