Reputation: 97
On a RHEL 6.7 server running Python 2.6.6 I am trying to start and stop the Apache webserver as an unprivileged user in a Python script.
The command I am using is "sudo service httpd " where parameter is "start", "stop" or "status".
p = subprocess.Popen("sudo service httpd start", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
This line alone does not work. Adding a
p.communicate()
lets the commands work as desired. Can somebody tell me why?
UPDATE: The sudoers file contains a line that allows my user to run these commands passwordless.
Upvotes: 1
Views: 5699
Reputation: 414245
Neither code works (with and without .communicate()
).
You should use instead (assuming passwordless sudo
for these commands):
import subprocess
subprocess.check_call("sudo service httpd start".split())
The reasons:
subprocess
functions do not run the shell by default and therefore the string is interpreted as a name of the command: you should use a list to pass multiple command-line arguments on POSIXPopen()
starts the command and returns immediately without waiting for it to finish i.e., it may happen before httpd is started. Assuming Popen()
call is fixed, .communicate()
waits for the child process to terminate and therefore it returns after httpd is started (whether it was successful or not).Upvotes: 3
Reputation: 176
There are different reasons for that to happen: 1. the user is in sudoers and configured to not insert password.
does it work in a brand new terminal session?
Upvotes: 0