Execute Linux commands in C/Python and obtain the returned values and outputs.

Source: Internet
Author: User

In general, the convenience of using shell is that it can directly call Linux system commands to conveniently get results.

But shell scprit has many constraints (I will not talk about it here ). The following describes how to call Linux commands in c and python, obtain the return value, and obtain the output.

1. Python, using the OS Library/commands Library

Method 1) Use the commands. getstatusoutput method. This is a magic method that can directly obtain the return value and command output. Official Website Description: http://docs.python.org/library/commands.html

Import osimport commands status, output = commands. getstatusoutput (writable Str) # ********************** the following code determines the return value *********** **************************************** * ****** if false = OS. wifexited (Status) or 0! = OS. wexitstatus (Status): self.logging.info ("Check port false. port [% s] has not been listened. reverse STR: [% s] ", port, reverse Str) return false self.logging.info (" Check port true. port [% s] has been listened. reverse STR: [% s] ", reverse Str) return true status is the return value, and ouput is the output # But this method has a problem, that is, if the command (reverse Str) contains the & symbol, this command will cause an error. In this case, you need to use OS. system Method

Method 2) use OS. System

Status = OS. System (writable Str)

Status is the return value and cannot be output. The check method is as follows:

 

Method 3) Use OS. popen, which is similar to C, to get both the return value and the output. The disadvantage is that it is a little troublesome to use.

p=os.popen('ssh 10.3.16.121 ps aux | grep mysql')x=p.read()print xp.close()

P is equivalent to an opened file.

Method 4) Use
SubprocessModule, which is a relatively new module to replace

os.systemos.spawn*os.popen*popen2.*commands.*

These modules. Subprocess application instance:

Subprocess.Call(ARGs,
*,Stdin = none,Stdout = none,Stderr = none,
Shell = false
)

import subprocesscmd=['ls','-l']subprocess.call(cmd)subprocess.call('cat /etc/passwd',shell=True)

2. Use the # include <stdio. h> library in C. Below is a function that calls system commands.

With popen, the advantage is that both the returned value and the output can be obtained. I encapsulate the call and return value judgment for ease of use at ordinary times.

#include <stdio.h> int execute_cmd(const char *cmdstr, char * retstr, int len)                       {                                                                                   FILE *fpin=NULL;                                                            if(NULL==(fpin=popen(cmdstr,"r")))                                    {                                                                                   WRITE_LOG_EX(UL_LOG_FATAL,"execute command '%s' failed: %s",cmdstr,strerror(errno));          return 1;                                                                 }                                                                                                                                                                    if(NULL == fgets(retstr, len, fpin))                                               {                                                                                           retstr = NULL;                                                           }                                                                              return 0;                                                                      } 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.