python中执行linux命令(调用linux命令)

172 篇文章 1 订阅

转自:http://blog.csdn.net/laiahu/article/details/6697930

python中执行linux命令

python中执行linux命令:

os.system(cmd)

如果要把返回信息置入变量中:

textlist = os.popen(cmd)

例:

cmd = 'ps -ef '
textlist = os.popen(cmd).readlines()
for line in textlist:
           ......






转自:http://fsldn.blog.163.com/blog/static/454643201092814425453/

Python中执行系统命令常见方法有两种:

两者均需 import os

(1) os.system

# 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息

system(command) -> exit_status
Execute the command (a string) in a subshell.

# 如果再命令行下执行,结果直接打印出来

 
1>>> os.system('ls')
204101419778.CHM   bash      document    media      py-django   video
311.wmv            books     downloads   Pictures  python
4all-20061022      Desktop   Examples    project    tools

(2) os.popen

# 该方法不但执行命令还返回执行后的信息对象

popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.

例如:

 
01>>>tmp = os.popen('ls *.py').readlines()
02>>>tmp
03Out[21]:
04['dump_db_pickle.py ',
05'dump_db_pickle_recs.py ',
06'dump_db_shelve.py ',
07'initdata.py ',
08'__init__.py ',
09'make_db_pickle.py ',
10'make_db_pickle_recs.py ',
11'make_db_shelve.py ',
12'peopleinteract_query.py ',
13'reader.py ',
14'testargv.py ',
15'teststreams.py ',
16'update_db_pickle.py ',
17'writer.py ']

好处在于:将返回的结果赋于一变量,便于程序的处理。

(3)  使用模块subprocess

 
1>>> import subprocess
2>>> subprocess.call (["cmd""arg1""arg2"],shell=True)

获取返回和输出:

 
1import subprocess
2= subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
3for line in p.stdout.readlines():
4    print line,
5retval = p.wait()

(4)  使用模块commands模块

 
1>>> import commands
2>>> dir(commands)
3['__all__''__builtins__''__doc__''__file__''__name__''getoutput''getstatus''getstatusoutput','mk2arg''mkarg']
4>>> commands.getoutput("date")
5'Wed Jun 10 19:39:57 CST 2009'
6>>>
7>>> commands.getstatusoutput("date")
8(0'Wed Jun 10 19:40:41 CST 2009')

注意: 当执行命令的参数或者返回中包含了中文文字,那么建议使用subprocess,如果使用os.popen则会出现下面的错误:

 
1Traceback (most recent call last):
2  File "./test1.py", line 56, in <module>
3    main()
4  File "./test1.py", line 45, in main
5    fax.sendFax()
6  File "./mailfax/Fax.py", line 13, in sendFax
7    os.popen(cmd)
8UnicodeEncodeError: 'ascii' codec can't encode characters in position 46-52: ordinal not in range(128)



转自:http://www.linuxidc.com/Linux/2012-08/67787.htm

Python调用shell命令

1.1   os.system(command)

在一个子shell中运行command命令,并返回command命令执行完毕后的退出状态。这实际上是使用C标准库函数system()实现的。这个函数在执行command命令时需要重新打开一个终端,并且无法保存command命令的执行结果。

1.2   os.popen(command,mode)

打开一个与command进程之间的管道。这个函数的返回值是一个文件对象,可以读或者写(由mode决定,mode默认是’r')。如果mode为’r',可以使用此函数的返回值调用read()来获取command命令的执行结果。

os.system(cmd)或os.popen(cmd),前者返回值是脚本的退出状态码,后者的返回值是脚本执行过程中的输出内容。实际使用时视需求情况而选择。

1.3   commands.getstatusoutput(command)

  使用commands.getstatusoutput函数执行command命令并返回一个元组(status,output),分别表示command命令执行的返回状态和执行结果。对command的执行实际上是按照{command;} 2>&1的方式,所以output中包含控制台输出信息或者错误信息。output中不包含尾部的换行符。

实例:

>>>import commands

>>> status, output = commands.getstatusoutput('ls -l')

使用subprocess模块可以创建新的进程,可以与新建进程的输入/输出/错误管道连通,并可以获得新建进程执行的返回状态。使用subprocess模块的目的是替代os.system()、os.popen*()、commands.*等旧的函数或模块。

2.1   subprocess.call(["some_command","some_argument","another_argument_or_path"])

subprocess.call(command,shell=True)

实例:

handle = subprocess.call('ls -l', shell=True)

2.2   subprocess.Popen(command, shell=True)

如果command不是一个可执行文件,shell=True不可省。

  最简单的方法是使用class subprocess.Popen(command,shell=True)。Popen类有Popen.stdin,Popen.stdout,Popen.stderr三个有用的属性,可以实现与子进程的通信。 【Linux公社 http://www.linuxidc.com 】

将调用shell的结果赋值给python变量

handle = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)

实例:

handle = subprocess.Popen('ls -l', stdout=subprocess.PIPE, shell=True)

handle = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE, shell=True)

handle = subprocess.Popen(args='ls -l', stdout=subprocess.PIPE, shell=True)

print handle.stdout.read()

print handle.communicate()[0]





转自:http://hi.baidu.com/gloria_kevin/item/d611868f27fe37834514cf3b

在C/python中执行linux命令并得到返回值以及输出

一般来说,用shell的方便之处在于,能够直接调用linux系统命令,方便的得到结果。

但是shell scprit的约束重重(这里不再讲了)。下面说一下在C和python中如何调用linux命令、得到返回值并得到输出

1. python,使用os库/commands库

import os

import commands

方法1)使用commands.getstatusoutput方法,这是一个神奇的方法,能够直接得到返回值以及命令输出。官网说明:http://docs.python.org/library/commands.html

        status,output=commands.getstatusoutput(cmdstr)

***********************下面代码是判断返回值**********************************************************

        if False==os.WIFEXITED(status) or 0!=os.WEXITSTATUS(status):                       
            self.logging.info("check port false. port [%s] has not been listened. cmdstr: [%s]", port, cmdstr)                                                        
            return False 
        self.logging.info("check port true. port [%s] has been listened. cmdstr: [%s]", cmdstr) 
        return True       

status是返回值,ouput是输出

但是这种方法存在一个问题,就是如果命令中(cmdstr)含有&符号,这个命令会出错,此时,需要使用os.system方法

 

方法2)使用os.system

status = os.system(cmdstr)

status是返回值,得不到输出,检查的方法如上

 

方法3)使用os.popen,这是一个和C相似的方法,既能得到返回值,也能得到输出,缺点是用起来稍微麻烦一些

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

p相当于打开的一个文件

 

2. C中使用#include <stdio.h> 库,下面是我写的一个调用系统命令的函数。

使用popen,这个好处就是既能得到返回值也能得到输出,我将调用以及返回值判断封装了一下,便于平时使用

#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;                                                                      
}





转自:http://blog.sina.com.cn/s/blog_a04184c101010ksf.html

Python : 使用Python调用Linux系统命令

一个好玩的,以python方式来调用系统命令,只要命令在当前PATH中即可

用这个模块,一些shell脚本可以很方便的用python来写

>>> import pbs

>>> pbs.pwd()

/var/log

>>> pbs.hostname()

waf-dev

>>> pbs.ifconfig('eth1')

eth1      Link encap:以太网  硬件地址 00:50:56:94:db:20

          inet 地址:182.168.1.1  广播:192.2.255.255  掩码:255.255.0.0

          inet6 地址: fe80::250:56ff:fe94:db20/64 Scope:Link

          UP BROADCAST RUNNING MULTICAST  MTU:1500  跃点数:1

          接收数据包:3229133 错误:0 丢弃:0 过载:0 帧数:0

          发送数据包:2215454 错误:0 丢弃:0 过载:0 载波:0

          碰撞:0 发送队列长度:1000

          接收字节:452148544 (452.1 MB)  发送字节:1095951536 (1.0 GB)

>>> pbs.ping('g.cn', c=3)

PING g.cn (203.208.45.208) 56(84) bytes of data.

64 bytes from 203.208.45.208: icmp_seq=1 ttl=48 time=13.1 ms

64 bytes from 203.208.45.208: icmp_seq=2 ttl=48 time=12.4 ms

64 bytes from 203.208.45.208: icmp_seq=3 ttl=48 time=11.6 ms

--- g.cn ping statistics ---

3 packets transmitted, 3 received, 0% packet loss, time 2003ms

rtt min/avg/max/mdev = 11.675/12.430/13.125/0.593 ms





转自:http://bbs.chinaunix.net/thread-4054722-1-1.html

java中调用linux命令:

我刚才试了一下,jvm拦截了所有stdout/stderr
.exec()返回了Process对象,从中得到inpustream,另启线程输出即可
这时我刚才测试的代码:

/**
 * 
 */
package darrenlee.test.cu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author darrenlee
 * 
 */
public class Command implements Runnable {

        private InputStream in;

        public Command(InputStream in) {
                this.in = in;
        }

        /**
         * @param args
         */
        public static void main(String[] args) {
                try {
                        Process p = Runtime.getRuntime().exec("ping -c 10 127.0.0.1");
                        //Process p = Runtime.getRuntime().exec("ifconfig");
                        InputStream in = p.getInputStream();
                        Command r = new Command(in);
                        new Thread(r).start();
                } catch (IOException e) {
                        e.printStackTrace();
                }
        }

        @Override
        public void run() {
                BufferedReader bufferedReader = new BufferedReader(
                                new InputStreamReader(in));
                try {
                        String line = bufferedReader.readLine();
                        while (line != null) {
                                System.out.println(line);
                                line = bufferedReader.readLine();
                        }
                        bufferedReader.close();
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }

}



  • 6
    点赞
  • 80
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值