python模块:调用系统命令模块subprocess等
http://blog.csdn.net/pipisorry/article/details/46972171
Python经常被称作“胶水语言”,因为它能够轻易地操作其他程序,轻易地包装使用其他语言编写的库。在Python/wxPython环境下,执行外部命令或者说在Python程序中启动另一个程序的方法。
1、os.system(command)
os.system()函数用来运行shell命令。此命令可以方便的调用或执行其他脚本和命令
这个调用相当直接,且是同步进行的,程序需要阻塞并等待返回。返回值是依赖于系统的,直接返回系统的调用返回值,所以windows和linux是不一样的。
如果filename字符串中有空格,则会出现错误:File Not Found错误
可以通过下面 前面三个方法只能用于执行程序和打开文件,不能处理URL,打开URL地址可用webbrowser模块提供的功能。 调用系统缺省浏览器打开URL地址,如 webbrowser.open('http://www.jb51.net'),也可以利用 举个栗子 >>> import os 可以看出,popen方法通过p.read()获取终端输出,而且popen需要关闭close().当执行成功时,close()不返回任何值,失败时,close()返回系统返回值. 可见它获取返回值的方式和os.system不同。 举个栗子 >>> import commands 根据你需要的不同,commands模块有三个方法可供选择。getstatusoutput, getoutput, getstatus。 当我们运行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的一些功能做一些转义。: 例子 如果你更关注命令的终端输出,可以这样 >>> subprocess.check_output(["echo", "Hello World!"]) >>> subprocess.check_output("exit 1", shell=True) Traceback (most recent call last): python3.5最新语法及示例 subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False) 更复杂的命令使用,如 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 input The input argument is passed to input相当于一个文件中的内容,而不是命令的参数! 使用代码中的变量
好像可以通过stdin输入代码中的变量,但是更简单的也可以直接使用下面的字符串连接实现 指定子进程工作路径 Note: 上一条run修改当前路径对下一条run是没用的 获取Popen的返回值及输出 import sys,os,subprocess,commands subprocess还有另一种更简单方法,效果一样,它会返回stdout s = subprocess.check_output('ls -l', shell=True) [ [Python标准库06 子进程 (subprocess包)] [Python模块整理(三):子进程模块subprocess] Python和其他进程的管道通信方式--popen和popen2的比较 lz发现了一个相当不错的库amoffat/sh,可以用 Python 函数的语法去调用 shell 命令,sh 之于 subprocess 类似 requests 之于 urllib2。 pip3 install sh sh库用来将shell命令作为函数导入到Python中。在bash中使用是非常实用的,但是在Python中不容易记住怎么使用(即递归搜索文件)。 使用示例 from sh import find from sh import git [sh:sh 1.08 — sh v1.08 documentation] from:http://blog.csdn.net/pipisorry/article/details/46972171 ref:python中执行linux命令(调用linux命令) python常用模块-调用系统命令模块(subprocess) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. subproces基本上就是为了取代os.system和os.spaw ... 除了常见的os.system和os.popen方法,官方强烈推荐使用subprocess来调用系统命令. 这个库用起来其实很简单,按照惯例先贴一下官文关键点: The subprocess modul ... 一.一般调用流程 http://www.cnblogs.com/huangshujia/p/4394276.html 二.Python读取图像并传入C++函数,再从C++返回结果图像给Python h ... 一. 引用模块在 父+级目录中: 1. 将导入模块所在目录(../model/模块)添加到系统环境变量path下,可添加多个 import syssys.path.append("../mo ... 5.13 跨模块调用 在开发过程中经常会在当前模块调用其他模块的方法,这个时候就涉及到跨模块调用,我们还可以了解到A和R两个快捷方法的使用.例如,我们在Index模块调用User模块的操作方法 c ... ThinkPHP 跨模块调用操作方法(A方法与R方法) 跨模块调用操作方法 前面说了可以使用 $this 来调用当前模块内的方法,但实际情况中还经常会在当前模块调用其他模块的方法.ThinkPHP 内 ... thinkphp跨模块调用 跨模块调用模板 return $view->fetch('admin@user/add'); 全路径模板调用: return $view->fetch(APP_ ... 概述 使用rust-cpython将rust程序做为python模块调用: 通常为了提高python的性能: 参考 https://github.com/dgrunwald/rust-cpython ... Python 调用系统命令的模块 Subprocess 有些时候需要调用系统内部的一些命令,或者给某个应用命令传不定参数时可以使用该模块. 初识 Subprocess 模块 Subprocess 模块 ... 程序片段(01):全排列.c 内容概要:全排列密码库 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <std ... gradle 简介 基于Groovy实现的自动化构建工具,比maven好的一点在于不用写复杂的xml文件.使用script就可以. gradle 专业名词 从一个build.gradle 文件开始,b ... 写在前面 之前的一个博文里分享了日本Unity酱的项目,如果大家有去仔细搜Unity酱的话,就会发现日本Unity官方还放出了一个更完整的Unity酱的项目,感觉被萌化了!(事实上,Unity日本经常 ... 1) try 'there will be' instead of 'then' In homogeneity MRF, if and , there will be even if . 2) in ... 简介 最近CSDN支持Markdown语法写博客了,甚是欢喜.前几天写了一篇实验了下,感觉不错.准备写几篇文章介绍一下如何使用CSDN的Markdown编辑器写博客,不求全面,但求够用,望大家批评指正 ... 摘要:分享牛系列.分享牛转载.第三方支付,java第三方支付.android第三方支付. 原文地址:http://blog.csdn.net/zwl5670/article/details/51219 ... MainActivity.java package com.qf.day23_service_demo2; import android.app.Activity; import android.co ... 为什么会有这个需求就不用我多说了吧:) 目前在驱动中提权我知道的有三种办法 1. 该方法来源于stoned bootkit,主要原理是把services.exe的EPROCESS中的Token值取出来 ... 1 添加Box2D相关的库 步骤1:右击项目所在的解决方案à添加->现有项目àE:\Installed\cocos2d-x-3.2\cocos2d-x-3.2\external\Box2D ... package com.exam1ple.demo1; import android.app.Activity; import android.app.NotificationManager; imp ...[
4、webbrowser.open(url)
webbrowser.open('h:\python.zip')来执行程序。这样可以不必区分是文件名还是URL,不知道在Linux下是否可行。
以上在Windows2000,Python2.4a1,wxPython 2.5.1运行。
[python调用shell的方法]5. os.popen(command[,mode[,bufsize]])
>>> 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
>>>6. 使用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'7. Python文档中目前全力推荐第四个方法subprocess
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.
import subprocess
new_filename = '/tmp/b'
filename = '/tmp/a'
subprocess.call(['mv', filename, new_filename])
subprocess.call([
subprocess.call(r'..\Scripts\activate', shell=True)
subprocess.call('scrapy crawl dmoz')
'Hello World!\n'
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1>>> 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')
参数使用
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命令查看
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.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) # 无输出
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)
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)
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 — Subprocess management]8. 还有两种方法:os.spawn* 和 popen2.*。它们也可以完成同样的任务
9. sh : Python subprocess interface
find("/tmp")
/tmp/foo
/tmp/foo/file1.json
/tmp/foo/file2.json
/tmp/foo/file3.json
/tmp/foo/bar/file3.json
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'))
python模块:调用系统命令模块subprocess等的更多相关文章
随机推荐