开发者

Passing output from subprocess.Popen to a if elif statement

Im creating a python script to check for suPHP i'm trying to create an if else statement to declare if suPHP is on the server using output from subprocess.Popen

I've tested the output of the variab开发者_高级运维le with print before i created this post and it pass's the correct output to the variable suphp. This is what i have so far:

# check for suPHP
suphp =  subprocess.Popen("/usr/local/cpanel/bin/rebuild_phpconf --current", shell=True, stdout=subprocess.PIPE,).communicate()[0]

 if suphp = "/bin/sh: /usr/local/cpanel/bin/rebuild_phpconf: No such file or directory"          
    print "suPHP is not installed on the server"
 elif
    print suphp

Please note I am new to coding and python and decided to try to use python to admin some servers.


You don't appear to be doing anything useful with the shell=True, and so you can probably safely skip it alltogether:

try:
    suphp = subprocess.Popen(["/usr/local/cpanel/bin/rebuild_phpconf", "--current"], 
                             stdout=subprocess.PIPE,).communicate()[0]
except OSError:
    print "Couldn't start subprocess, suPHP is not installed on the server"

note that you'll have to split the command into each of its separate arguments, since you won't have a shell to do it for you. You should always avoid using the shell for subprocesses unless you absolutely require it (say, because you have to set your environment by sourcing a script)


Out of my head:

the comparison operator is == not = and output is almost always followed by a newline character.

so try something like this:

if "No such file or directory" in suphp:
    ...


In Unix, you sometimes need to consider that subprocesses can output text to two different output streams. When there are no problems, like with echo hello, the text gets sent to the "standard output" stream.

On the other hand, it's considered good manners for a process to send all of its error messages to the "standard error" stream; for example stat /this-file-does-not-exist. You can verify this by sending all standard output to /dev/null.

When you run this command, you'll get no output on your console:

stat . > /dev/null

When you run this, an error message will appear on your console (because the text is from the standard error stream):

sh /this-program-does-not-exist > /dev/null

Getting back to your question, the "standard error" stream is sometimes called "stderr". The text from this stream can be captured using Python's subprocess library using the POpen.stderr property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜