Solve the problem that python can't get the return value when executing shell command

  • 2021-08-17 00:14:04
  • OfStack

Problem Background: When using python to obtain supervisor status information in the server, it was found that the return value could not be obtained.

python There are several ways to get the value returned after executing the shell command:


# 1.os Module 
ret = os.popen("supervisorctl status")
ret_data = ret.read()
# 2.subprocess Module 
ret = subprocess.Popen('supervisorctl status',shell=True,stdout=subprocess.PIPE)
out,err = ret.communicate()
# 3.commands Module 
ret_data = commands.getoutput("supervisorctl status")
# commands.getstatusoutput() You can also get the status of whether the command execution is successful or not 

The first program uses os. popen () method, and the return value of execution can be obtained by using the above methods in interactive python, shell or IDE environment. However, when using script execution, the return value is found to be empty, and then it is modified to use command. getoutput () method, and the return value is "sh: supervisorctl: command not found".

It can be seen that the supervisorctl command cannot be recognized when executing the command, but supervisor has been installed in the system, so which supervisorctl is used to view the supervisorctl path, and the instruction "/usr/local/bin/supervisorctl status" is executed with a path, and finally the return value is successfully obtained.

Summary:

python When using the shell command to operate non-system-built tools, it is best to bring the tool path.

Additional knowledge: How does python determine whether the calling system command was successfully executed

First, we need to know how to call system commands:


>>> os.system('ls')
anaconda-ks.cfg install.log.syslog  Template   Picture   Download   Desktop 
install.log      Public             Video   Document   Music 
0
>>>
>>> os.system('lss')
sh: lss: command not found
32512
>>>

\\ In the first case, we can recognize with naked eyes that the correct one will return 0, and the wrong one will return non-0

\\ Second, use if to judge whether the return value of calling system command is 0. If it is 0, it will not be output, and if it is not 0, it will output "Without the command"

----------------------


>>> if os.system('lss') !=0:print 'Without the command'
...
 
sh: lss: command not found
Without the command

----------------------


>>> if os.system('ls') !=0:print 'Without the command'
...
 
anaconda-ks.cfg install.log.syslog  Template   Picture   Download   Desktop 
install.log      Public             Video   Document   Music 
>>>

Related articles: