popen

python:调用bash

雨燕双飞 提交于 2020-01-28 01:12:02
利用os模块 python调用Shell脚本,有三种方法: os.system(cmd)返回值是脚本的退出状态码 os.popen(cmd)返回值是脚本执行过程中的输出内容 commands.getstatusoutput(cmd) 返回(status, output) http://www.jb51.net/article/55327.htm 1. os.system(command) 此函数会启动子进程,在子进程中执行command,并返回command命令执行完毕后的退出状态,如果command有执行内容,会在标准输出显示。这实际上是使用C标准库函数system()实现的。 缺点:这个函数在执行command命令时需要重新打开一个终端,并且无法保存command命令的执行结果。 实例:os.system('ls -l *') 2. os.popen(command,mode) 打开一个与command进程之间的管道。这个函数的返回值是一个文件对象,可以读或者写(由mode决定,mode默认是’r')。如果mode为’r',可以使用此函数的返回值调用read()来获取command命令的执行结果。 os.system(cmd)或os.popen(cmd),前者返回值是脚本的退出状态码,后者的返回值是脚本执行过程中的输出内容。实际使用时视需求情况而选择。 output = os

在Python里调用执行Linux或Windows系统的shell命令:system、popen、commands、subprocess

旧巷老猫 提交于 2020-01-27 14:14:59
Python 语言的灵活性和易用性,使得它非常适合作为“胶水”,去粘合各种系统命令(shell),完成复杂的运维工作和特殊场景的需求。本文主要介绍 Python 里如何调用执行 Linux 或 Windows 的系统命令(shell),方法主要有 system 、 popen 、 commands 和 subprocess 。 system os.system(cmd) ,这个方法使用起来最直接,是 同步 执行,会 阻塞 进程。所以,在需要返回结果的场景中,这个方法是最合适的。 但需要注意的是,其只返回执行得状态码(依赖于操作系统),其值为 int 类型, 0 表示 shell 执行成功, 256 则表示未找到命令。(状态码 Linux 和 Windows 是不一样的) 代码示例: import os status_code = os . system ( 'uptime' ) print ( 'status_code:' , status_code ) status_code : 0 popen os.popen(cmd [,mode [,bufsize]]) ,这个方法是以文件的形式返回 shell 命令执行后的结果,也是 同步 执行,会 阻塞 进程。 但与 os.system 的返回值不同, os.popen 通过 read() 或 readlines()

使用Python调用系统命令

[亡魂溺海] 提交于 2020-01-25 15:00:55
os.system() 该函数返回命令执行结果的返回值,system()函数在执行过程中进行了以下三步操作: 1、fork一个子进程; 2、在子进程中调用exec函数去执行命令; 3、在父进程中调用wait(阻塞)去等待子进程结束。 返回0表示命令执行成功,其他表示失败。 注意:使用该函数经常会莫名其妙地出现错误,但是直接执行命令并没有问题,所以一般建议不要使用。 用法:os.system("command") os.popen() 这种调用方式是通过管道的方式来实现,函数返回是 file read 的对象,对其进行读取read、readlines等操作可以看到执行的输出。 注意:如果命令执行失败,就读取不到内容。 用法:os.popen("command") subprocess.Popen() subprocess模块被推荐用来替换一些老的模块和函数,如:os.system、os.spawn*、os.popen*等 subprocess模块目的是fork一个新的进程并与之通信,最常用是定义类Popen,使用Popen可以创建进程,并与进程进行复杂的交互。其函数原型为: class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn

Python:如何得到Popen的输出?

左心房为你撑大大i 提交于 2020-01-18 00:34:09
最近在用subprocess中的Popen做个磁盘监控小程序,但是在使用ps = Popen("df -h", shell=True, stdout=PIPE, stderr=PIPE)之后,再使用output_lines = ps.stdout.readlines()的时候,output_lines总是内容为空,有哪位知道是什么原因么? btw:我是在windows下设计这个程序的 代码 # !/usr/bin/env python # coding=utf-8 from subprocess import Popen, PIPE import re def disk_space(pattern = " 2[0-9]% " , message = " CAPACITY WARNING " ): # # take shell command output ps = Popen( " df -h " , shell = True, stdout = PIPE, stderr = PIPE) output_lines = ps.stdout.readlines() for line in output_lines: line = line.strip() if re.search(pattern, line): print " %s %s " % (message, line) if

Multiple shell commands in python (Windows)

浪尽此生 提交于 2020-01-17 01:11:10
问题 I'm working on a windows machine and I want to set a variable in the shell and want to use it with another shell command, like: set variable = abc echo %variable% I know that I could do this using os.system(com1 && com2) but I also know, that this is considered 'bad style' and it should be possible by using the subprocess module, but I don't get how. Here is what I got so far: proc = Popen('set variable=abc', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT) proc.communicate(input=b'echo

Popen mixed data stream?

。_饼干妹妹 提交于 2020-01-16 19:37:06
问题 I've got problem with Popen and Pipes on Windows. I think Popen mixed data between stdout and stderr. When my program reads only stdout everything is OK but when I read stdout and stderr some data from stdout is thrown to stderr. My read method: for line in iter(self._read_obj.readline, b''): self._queue.put(line) sleep(.2) Where self._read_obj is either stderr or stdout. Do you know how can I solve this? 回答1: from subproccess import * x = Popen('sh /root/script.sh', stdout=PIPE, stderr=PIPE,

Terminating a program within a time frame through python

懵懂的女人 提交于 2020-01-15 09:52:48
问题 I'm running a fortran code from a python script which sometimes takes a while to run. Thus I'm limiting the run time with a code taken from this link: def timeout(func, args=(), kwargs={}, timeout_duration=15, default=1): import signal class TimeoutError(Exception): pass def handler(signum, frame): raise TimeoutError() # set the timeout handler signal.signal(signal.SIGALRM, handler) signal.alarm(timeout_duration) try: result = func(*args, **kwargs) except TimeoutError as exc: result = default

popen - locks or not thread safe?

寵の児 提交于 2020-01-15 06:30:34
问题 I've seen a few implementations of popen()/pclose(). They all used a static list of pids, and no locking: static int *pids; static int fds; if (!pids) { if ((fds = getdtablesize()) <= 0) return (NULL); if ((pids = malloc(fds * sizeof(int))) == NULL) return (NULL); memset(pids, 0, fds * sizeof(int)); } Or this, supposedly NetBSD: static struct pid { struct pid *next; FILE *fp; pid_t pid; } *pidlist; /* Link into list of file descriptors. */ cur->fp = iop; cur->pid = pid; cur->next = pidlist;

popen - locks or not thread safe?

为君一笑 提交于 2020-01-15 06:30:26
问题 I've seen a few implementations of popen()/pclose(). They all used a static list of pids, and no locking: static int *pids; static int fds; if (!pids) { if ((fds = getdtablesize()) <= 0) return (NULL); if ((pids = malloc(fds * sizeof(int))) == NULL) return (NULL); memset(pids, 0, fds * sizeof(int)); } Or this, supposedly NetBSD: static struct pid { struct pid *next; FILE *fp; pid_t pid; } *pidlist; /* Link into list of file descriptors. */ cur->fp = iop; cur->pid = pid; cur->next = pidlist;

When should I use subprocess.Popen instead of os.popen?

时间秒杀一切 提交于 2020-01-15 06:18:47
问题 Seems both executes a subprocess and create a pipe to do in/out, just that the subprocess is newer. My question is, is there any function that subprocess.Popen can do while os.popen cannot, so that we need the new module subprocess ? Why Python language didn't choose to enhance os.popen but created a new module? 回答1: Short answer: Never use os.popen , always use subprocess! As you can see from the Python 2.7 os.popen docs: Deprecated since version 2.6: This function is obsolete. Use the