http://blog.csdn.net/pipisorry/article/details/46972171

Python经常被称作“胶水语言”,因为它能够轻易地操作其他程序,轻易地包装使用其他语言编写的库。在Python/wxPython环境下,执行外部命令或者说在Python程序中启动另一个程序的方法。

1、os.system(command)

os.system()函数用来运行shell命令。此命令可以方便的调用或执行其他脚本和命令

  • #打开指定的文件
  • >>>os.system('notepad *.txt')
  • 这个调用相当直接,且是同步进行的,程序需要阻塞并等待返回。返回值是依赖于系统的,直接返回系统的调用返回值,所以windows和linux是不一样的。

    如果filename字符串中有空格,则会出现错误:File Not Found错误

    可以通过下面[

    
    

    [Python中subprocess学习]

    4、webbrowser.open(url)

    前面三个方法只能用于执行程序和打开文件,不能处理URL,打开URL地址可用webbrowser模块提供的功能。

    调用系统缺省浏览器打开URL地址,如 webbrowser.open('http://www.jb51.net'),也可以利用
    webbrowser.open('h:\python.zip')来执行程序。这样可以不必区分是文件名还是URL,不知道在Linux下是否可行。
    以上在Windows2000,Python2.4a1,wxPython 2.5.1运行。
    [python调用shell的方法]

    5. os.popen(command[,mode[,bufsize]])

    举个栗子

    >>> import os
    >>> p = os.popen("dir c:", 'r')
    >>> p.read()
    bla bla... <这里是dir正确的输出>
    >>> p.close()
    >>> p = os.popen("dir d:", 'r') # 电脑中没有D盘
    >>> p.read()
    ''
    >>> p.close()
    1
    >>>

    可以看出,popen方法通过p.read()获取终端输出,而且popen需要关闭close().当执行成功时,close()不返回任何值,失败时,close()返回系统返回值. 可见它获取返回值的方式和os.system不同。

    6. 使用commands模块

    举个栗子

    >>> 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'

    根据你需要的不同,commands模块有三个方法可供选择。getstatusoutput, getoutput, getstatus。

    皮皮blog

    7. Python文档中目前全力推荐第四个方法subprocess

    当我们运行python的时候,我们都是在创建并运行一个进程。正如我们在Linux进程基础中介绍的那样,一个进程可以fork一个子进程,并让这个子进程exec另外一个程序。在Python中,我们通过标准库中的subprocess包来fork一个子进程,并运行一个外部的程序(fork,exec见Linux进程基础)。

    subprocess包中定义有数个创建子进程的函数,这些函数分别以不同的方式创建子进程,所以我们可以根据需要来从中选取一个使用。另外subprocess还提供了一些管理标准流(standard stream)和管道(pipe)的工具,从而在进程间使用文本通信。

    使用subprocess包中的函数创建子进程的时候,要注意:

    1) 在创建子进程之后,父进程是否暂停,并等待子进程运行。

    2) 函数返回什么

    3) 当returncode不为0时,父进程如何处理。

    直接调用命令,返回值即是系统返回。

    shell命令中有一些是shell的内建命令,这些命令必须通过shell运行,$cd。shell=True允许我们运行这样一些命令。shell=True表示命令最终在shell中运行。Python文档中出于安全考虑,不建议使用shell=True。建议使用Python库来代替shell命令,或使用pipe的一些功能做一些转义。:

    例子

    import subprocess
    new_filename = '/tmp/b'
    filename = '/tmp/a'
    subprocess.call(['mv', filename, new_filename])
    subprocess.call([
    1. 启动virtualenv是一个shell命令,要在shell中执行。否则出错:WindowsError: [Error 193] %1 is not a valid Win32 application 2.  然而virtualenv中执行的命令并不是shell命令,不是在shell中执行的,直接运行即可。否则出错:'scrapy' is not recognized as an internal or external command,operable program or batch file.
    subprocess.call(r'..\Scripts\activate', shell=True)
    subprocess.call('scrapy crawl dmoz')

    如果你更关注命令的终端输出,可以这样

    >>> subprocess.check_output(["echo", "Hello World!"])
    'Hello World!\n'

    >>> subprocess.check_output("exit 1", shell=True)

    Traceback (most recent call last):
    ...
    subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

    python3.5最新语法及示例

    subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False)

    >>> subprocess.run(["ls", "-l"])  # doesn't capture output
    CompletedProcess(args=['ls', '-l'], returncode=0)
    
    >>> subprocess.run("exit 1", shell=True, check=True)
    Traceback (most recent call last):
      ...
    subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
    
    >>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
    CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
    stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')

    更复杂的命令使用,如

    subprocess.run( "cat ~/files/DATASETS/tianchi/ccf_data_revised/ccf_online_stage1_train.csv | cut -d ',' -f 1 | uniq | sort -n > /tmp/1.txt", shell=True)

    subprocess.run(r"mv '" + os.path.join(CA_DATASET_DIR, checkin_ca) + "' /tmp", shell=True)

    参数使用

    stdin和stdout

    import subprocess
    child1 = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE, cwd='/home/pipi')
    child2 = subprocess.Popen(["cat"], stdin=child1.stdout, shell=True)
    相当于将child1输出保存到一个文件,再使用child2的cat命令查看
    

    input

    The input argument is passed to Popen.communicate() and thus to thesubprocess’s stdin. If used it must be a byte sequence, or a string ifuniversal_newlines=True. When used, the internal Popen objectis automatically created with stdin=PIPE, and the stdin argument maynot be used as well.

    input相当于一个文件中的内容,而不是命令的参数!

    child2 = subprocess.run(["cat"], input = b'contents in a file', shell=True) # contents in a file
    child2 = subprocess.run(["echo"], input = b'contents in a file', shell=True) # 无输出

    使用代码中的变量

    好像可以通过stdin输入代码中的变量,但是更简单的也可以直接使用下面的字符串连接实现

    dir = '/home/pipi/files/DATASETS/tianchi/ccf_data_revised'
    train_filename = 'data_train2.txt'
    subprocess.run("cat " + train_filename + " | cut -d ',' -f 9 | sort| uniq -c", shell=True, cwd=dir)

    指定子进程工作路径

    Note: 上一条run修改当前路径对下一条run是没用的

    dir = '/home/pipi/files/DATASETS/tianchi/ccf_data_revised'
    subprocess.run("cat data_train2.txt | cut -d ',' -f 9 | sort| uniq -c", shell=True, cwd=dir)

    获取Popen的返回值及输出

    import sys,os,subprocess,commands
    from subprocess import Popen,PIPE
    p = Popen('python ' + path + '\getCurPath.py', stdout=PIPE, stderr=PIPE)
    p.wait()
    if(p.returncode == 0):
        print "stdout:%s" %p.stdout.read()

    subprocess还有另一种更简单方法,效果一样,它会返回stdout

    s = subprocess.check_output('ls -l', shell=True)

    [subprocess — Subprocess management]

    [Python标准库06 子进程 (subprocess包)]

    [Python模块整理(三):子进程模块subprocess]

    8. 还有两种方法:os.spawn* 和 popen2.*。它们也可以完成同样的任务

    Python和其他进程的管道通信方式--popen和popen2的比较

    9. sh : Python subprocess interface

    lz发现了一个相当不错的库amoffat/sh,可以用 Python 函数的语法去调用 shell 命令,sh 之于 subprocess 类似 requests 之于 urllib2。

    pip3 install sh

    sh库用来将shell命令作为函数导入到Python中。在bash中使用是非常实用的,但是在Python中不容易记住怎么使用(即递归搜索文件)。

    使用示例

    from sh import find
    find("/tmp")
    /tmp/foo
    /tmp/foo/file1.json
    /tmp/foo/file2.json
    /tmp/foo/file3.json
    /tmp/foo/bar/file3.json

    from sh import git
    git.clone("https://github.com/amoffat/sh")

    from sh import ls, mv
    
    new_filename = r'/tmp/b'
    filename = r'/tmp/a'
    try:
        mv(filename, new_filename)
    except:
        pass
    print(ls('/tmp'))

    [sh:sh 1.08 — sh v1.08 documentation]

    [python sh库实现分析]

    from:http://blog.csdn.net/pipisorry/article/details/46972171

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

    6方法,python中执行shell命令

    python模块:调用系统命令模块subprocess等的更多相关文章

    1. python常用模块-调用系统命令模块(subprocess)

      python常用模块-调用系统命令模块(subprocess) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. subproces基本上就是为了取代os.system和os.spaw ...

    2. 调用系统命令之subprocess模块

      除了常见的os.system和os.popen方法,官方强烈推荐使用subprocess来调用系统命令. 这个库用起来其实很简单,按照惯例先贴一下官文关键点: The subprocess modul ...

    3. 在Python中调用C++模块

      一.一般调用流程 http://www.cnblogs.com/huangshujia/p/4394276.html 二.Python读取图像并传入C++函数,再从C++返回结果图像给Python h ...

    4. Python多层目录模块调用

      一. 引用模块在 父+级目录中: 1. 将导入模块所在目录(../model/模块)添加到系统环境变量path下,可添加多个 import syssys.path.append("../mo ...

    5. thinkphp 跨模块调用

      5.13 跨模块调用   在开发过程中经常会在当前模块调用其他模块的方法,这个时候就涉及到跨模块调用,我们还可以了解到A和R两个快捷方法的使用.例如,我们在Index模块调用User模块的操作方法 c ...

    6. ThinkPHP 跨模块调用操作方法(A方法与R方法)

      ThinkPHP 跨模块调用操作方法(A方法与R方法) 跨模块调用操作方法 前面说了可以使用 $this 来调用当前模块内的方法,但实际情况中还经常会在当前模块调用其他模块的方法.ThinkPHP 内 ...

    7. thinkphp跨模块调用

      thinkphp跨模块调用 跨模块调用模板 return $view->fetch('admin@user/add'); 全路径模板调用: return $view->fetch(APP_ ...

    8. 4.1 python中调用rust程序

      概述 使用rust-cpython将rust程序做为python模块调用: 通常为了提高python的性能: 参考 https://github.com/dgrunwald/rust-cpython ...

    9. Python 调用系统命令的模块 Subprocess

      Python 调用系统命令的模块 Subprocess 有些时候需要调用系统内部的一些命令,或者给某个应用命令传不定参数时可以使用该模块. 初识 Subprocess 模块 Subprocess 模块 ...

    随机推荐

    1. Spark Streaming中的操作函数分析

      根据Spark官方文档中的描述,在Spark Streaming应用中,一个DStream对象可以调用多种操作,主要分为以下几类 Transformations Window Operations J ...

    2. logstash分析日志

      待处理日志格式如下: [totalCount: 298006556, count: 287347623, queryCount: 259027994, exeCount: 28319629, tota ...

    3. Ubuntu LTS 系统学习使用体会和实用工具软件汇总 6.04 8.04 10.04 12.04 14.04 16.04

      Ubuntu LTS 系统学习体会和工具软件汇总 6.04 8.04 10.04 12.04 14.04 16.04 ubuntu入门必备pdf:http://download.csdn.net/de ...

    4. Maven坐标机制

      Maven为所有的项目引入了坐标,基于坐标机制可以唯一定位一个项目. 坐标详解 以spring-core-2.5.6.jar的坐标定义为例,说明组成坐标的所有元素:groupId.artifactId ...

    5. The packages can be overrided by Java Endorsed Standards

       Endorsed Standards APIs The Endorsed Standards for Java SE constitute all classes and interfaces ...

    6. VisualStudio2010配置OpenCV的一种一劳永逸的方法

      用VS使用OpenCV的时候,又不想全局配置,每次都要配置简直烦死了. 鉴于此,给大家介绍一种简便一点的方法. 配置环境的前提是:成功安装了OpenCV合适的版本. 我这里用的是OpenCV2.4.9 ...

    7. 2.Cocos2dx 3.2中的重力系统Box2D

       1 添加Box2D相关的库 步骤1:右击项目所在的解决方案à添加->现有项目àE:\Installed\cocos2d-x-3.2\cocos2d-x-3.2\external\Box2D ...

    8. Android-满屏幕拖动的控件

      本文转载自师兄一篇博客:http://blog.csdn.net/yayun0516/article/details/52254818 觉得跟之前的模拟小火箭很相似,又有学习的地方,能作为知识补充.所 ...

    9. Swift基础之对FMDB第三方的使用方法

      相信大家都熟悉OC使用FMDB第三方库,进行数据库操作,增.删.改.查,现在我就来利用代码展示一下Swift对此库的使用方法,我是通过Pods添加的第三方库,如果手动添加记得创建桥接文件,在文件中调用 ...

    10. Retrofit2.0 ,OkHttp3完美同步持久Cookie实现免登录(二)

      原文出自csdn: http://blog.csdn.net/sk719887916/article/details/51700659: 通过对Retrofit2.0的<Retrofit 2.0 ...