笔记-python中调用其他程序---os.system os.popen subprocess.popen的使用

在python脚本中调用其他程序,或执行命令行指令,可以用os.system,os.popen,subprocess.popen这三种方式。这三种方式所适用的情况各不相同。区别在于调用程序后执行的操作,函数返回的是调用程序的输出,还是程序运行的状态码。

 

1.os.system

import os

原型:
os.system(command)

command --- 调用的命令
         该函数创建子进程调用其他程序,并在父进程中wait()子进程结束,command调用的程序产生输出,将会被打印在屏幕上(stdout),函数返回值是指令或程序执行的状态码。该函数通常用于一些简单的命令执行。

参考文档 

os.system(command)

Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command. If command generates any output, it will be sent to the interpreter standard output stream.

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

On Windows, the return value is that returned by the system shell after running command. The shell is given by the Windows environment variable COMSPEC: it is usually cmd.exe, which returns the exit status of the command run; on systems using a non-native shell, consult your shell documentation.

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

Availability: Unix, Windows.

import os
res = os.system("echo \"helloworld\"")

 

2.os.popen

import os

原型:

os.popen(command,mode,buf)
command --- 调用的命令
mode --- 模式权限可以是 'r'(默认) 或 'w'
bufsize -- 指明了文件需要的缓冲大小:0意味着无缓冲(默认),1意味着行缓冲,其它正值表示缓冲区大小,负的bufsize表示使用系统的默认值(0)。

       该函数创建子进程调用其他程序,父进程不会wait()子进程结束,而是在调用os.popen()之后继续执行,command调用程序产生输出,将会通过文件对象返回,该函数返回值是一个文件对象。可以对该文件对象进行读f.read()写f.write()操作,获取程序输出或者对程序输入。该函数不会获取程序状态码。
 

参考文档

os.popen(cmdmode='r'buffering=-1)

Open a pipe to or from command cmd. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The buffering argument has the same meaning as the corresponding argument to the built-in open() function. The returned file object reads or writes text strings rather than bytes.

The close method returns None if the subprocess exited successfully, or the subprocess’s return code if there was an error. On POSIX systems, if the return code is positive it represents the return value of the process left-shifted by one byte. If the return code is negative, the process was terminated by the signal given by the negated value of the return code. (For example, the return value might be - signal.SIGKILL if the subprocess was killed.) On Windows systems, the return value contains the signed integer return code from the child process.

This is implemented using subprocess.Popen; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.

import os
f = os.popen("echo \"helloworld\"")
f.read()

 

3.subprocess.Popen

import subprocess

原型:

subprocess.Popen( args, 
      bufsize=0, 
      executable=None,
      stdin=None,
      stdout=None, 
      stderr=None, 
      preexec_fn=None, 
      close_fds=False, 
      shell=False, 
      cwd=None, 
      env=None, 
      universal_newlines=False, 
      startupinfo=None, 
      creationflags=0)

args --- 是调用的命令,如果命令中有参数,需要使用列表的形式(List)传递
bufsize --- 表示缓冲大小:0表示无缓冲(默认),1表示行缓冲,其它正值表示缓冲区大小,负的bufsize表示使用系统的默认值(0)。
executable ---  指定要执行的程序。它很少会被用到:一般程序可以由args 参数指定。
stdin stdout和stderr --- 分别表示子程序的标准输入、标准输出和标准错误。可选的值有subprocess.PIPE或者一个有效的文件描述符,或者一个文件对象。如果是PIPE,则表示需要创建一个新的管道。另外,stderr的值还可以是STDOUT,表示子进程的标准错误也输出到标准输出。
shell --- 如果把shell设置成True,指定的命令会在shell里解释执行。windows下执行cmd指令,需要shell=True,运行程序则不用。

该函数提供了更加灵活的调用方式,用于替代上述两种函数。

参考文档:https://docs.python.org/3/library/subprocess.html#module-subprocess

● 使用PIPE获取程序输出

p = subprocess.Popen(['echo','helloworld'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
p.stdout.read()

● 获取程序的状态码

code = p.returncode

● p.communicate()

使用该方法,父进程会调用wait()等待程序结束后返回,一般使用该方法来等待程序结束,并接收程序的输出。

p = subprocess.Popen(['echo','helloworld'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out =p.communicate()
out.read()

● 注意:

使用管道获取程序输出时,会受到缓冲区影响,当缓冲区被写满,而没有从管道读出数据,程序会被阻塞。尤其是在使用主动调用wait()函数时,注意死锁的产生。推荐使用p.communicate()来获取缓冲区的输出。

 

当程序有大量输出时,推荐使用临时文件来获取输出。

out_temp = tempfile.TemporaryFile(mode='wb+')
fileno = out_temp.fileno()
p = subprocess.Popen("command",stdout=fileno,stderr = fileno)
#等待程序结束,并返回状态码
errorlevel = p.wait()
#获取程序的输出
out_temp.seek(0)
out= out_temp.read()

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
`os.system`、`os.popen`和`subprocess.Popen`都是用于在Python程序调用系统命令的函数,但是它们在用法和功能上有所不同。 1. `os.system` `os.system`函数用于在操作系统执行命令,并返回执行结果。它的使用方法是: ```python import os os.system('command') ``` 其,`command`是要执行的命令,可以是任何在操作系统可执行的命令。`os.system`函数将返回命令的退出状态码,通常情况下,0表示执行成功,其他值表示执行失败。 2. `os.popen` `os.popen`函数用于在操作系统执行命令,并返回命令的输出。它的使用方法是: ```python import os output = os.popen('command').read() ``` 其,`command`是要执行的命令,`output`是命令的输出结果,它是一个字符串类型的变量。`os.popen`函数将执行命令,并将命令的输出保存到`output`。 3. `subprocess.Popen` `subprocess.Popen`函数也用于在操作系统执行命令,但是它提供了更丰富的控制和选项。它的使用方法是: ```python import subprocess p = subprocess.Popen('command', stdout=subprocess.PIPE, shell=True) output, errors = p.communicate() ``` 其,`command`是要执行的命令,`stdout=subprocess.PIPE`表示将命令的输出保存到`output`,`shell=True`表示可以执行shell命令。`subprocess.Popen`函数将执行命令,并返回一个Popen对象,通过Popen对象可以控制命令的执行和获取命令的输出。 以上是三种调用系统命令的方法的区别和用法。总体来说,`os.system`函数用于简单的命令调用,`os.popen`函数用于获取命令的输出,`subprocess.Popen`函数用于更复杂的命令调用和控制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lmory233

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值