python调用调用Linux命令

发布时间:2019-07-09 09:32:48编辑:auto阅读(1854)

    如何调用Linux命令

    下面代码演示了调用一个shell命令, 其中,命令的输出会存储到result变量中, 而命令的返回值,则存储到exitcode中,由此可见,调用shell命令还是很方便的:


    import commands


    exitcode,result = commands.getstatusoutput('dir')


    print "exitcode: %s" %(exitcode)


    print "result: %s" %(result)


    命令行交互

    文件访问

    文件读写

    经常在网上复制代码块时,会将行号也复制下来, 为了去掉前面的行号,可以使用以下python脚本,这个脚本演示从一个文件读入,稍加处理写入到另一个文件:


    import os  

    import string  

    import re  

    import sys  

    args = sys.argv  


    infile=open(args[1],'r')  


    outfile=open(args[2],'w')  


    readline=infile.readlines()  


    infile.close()  


    for i in xrange(len(readline)):  


            line = readline[i]  


            line = line.strip()  


            strlist = line.split(' ')  

            del strlist[0]  

            line = ' '.join(strlist)  

            outfile.write(line + '\n')  

    outfile.close()

    检测目录与文件

    if os.path.exists("./setqt4env"):

            print "found!"

    网络访问

    http get

    通过网址抓内容,设置了30秒延时


    import socket

    import sys

    import urllib

    socket.setdefaulttimeout(30)

    try: 

        resp = urllib.urlopen("http://www.baidu.com")

    except Exception, info:

      print "Error '%s'" % (info[0])

    else:

        print (resp.read())

    ftp get

    自动ftp


    from ftplib import FTP


    ftp = FTP('192.168.1.61')


    ftp.login('user','password')


    ftp.retrbinary('RETR readme.txt', open("readme.txt", "wb").write)


    ftp.quit()

    调用C/C++

    写一个c++文件api.cpp:


    #include <Python.h>

    class MyClass {

    public:

        int add(int x,int y) { return x+y; }

    };

    extern "C" int add(int x,int y)

    {

        MyClass obj;

        return obj.add(x,y);

    }

    将c++编译成动态库:


    g++ -fPIC api.cpp -o api.so -shared -I/usr/include/python2.7 -I/usr/lib/python2.7/config

    在python中调用add函数:


    import ctypes

    plib = ctypes.CDLL('/tmp/api.so')

    print "result: %d" %(plib.add(1,2))

    系统调用

    虽然需求好像有点“过份”,但是强大的python是可以调用诸如ioctl这类的Linux系统调用的, 以下的例子是让蜂鸣器响:


    import fcntl

    fd = open('/dev/pwm', 'r')

    fcntl.ioctl(fd, 1, 100)

    等效于以下c代码


    int fd = open("/dev/pwm", O_RDONLY);

    ioctl(fd, 1, 100);

    IDE

    我只用过 PyCharm,跨平台的, 由于不做大型的开发,所以我只试用了基本的功能,例如:


    可以直接在界面上运行,无需切换到终端敲命令

    敲代码时有智能完成

    即时的语法检查

    光有这些就比一般的编辑器好太多了。

    Killer Apps

    Zope

    Zope是一个开源的web应用服务器,主要用python写成。它是一个事务型的对象数据库平台 Zope的管理面板首页Zope除了能储存内容,数据外,还能存放动态的HTML模板、脚本、搜索引擎、关系数据库管理系统(RDBMS)接口和代码。zope里的一切都是对象。它有一个强大的基于web的在线开发模板,使你能在世界上任何地方,任何时间方便地更新你的网站。

    1). commands.getstatusoutput(cmd)


    用os.popen()执行命令cmd, 然后返回两个元素的元组(status, result). cmd执行的方式是{ cmd ; } 


    2>&1, 这样返回结果里面就会包含标准输出和标准错误.



    2). commands.getoutput(cmd)


    只返回执行的结果, 忽略返回值.



    3). commands.getstatus(file)


    返回ls -ld file执行的结果.



    看一下这些函数使用的例子:


    >>> import commands


    >>> commands.getstatusoutput('ls /bin/ls')


    (0, '/bin/ls')


    >>> commands.getstatusoutput('cat /bin/junk')


    (256, 'cat: /bin/junk: No such file or directory')


    >>> commands.getstatusoutput('/bin/junk')


    (256, 'sh: /bin/junk: not found')


    >>> commands.getoutput('ls /bin/ls')


    '/bin/ls'

    >>> commands.getstatus('/bin/ls')


    '-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'


关键字