Python执行Linux系统命令的4种方法

作者:junjie 时间:2023-08-10 19:04:50 

(1) os.system

仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息


system(command) -> exit_status
Execute the command (a string) in a subshell.


如果再命令行下执行,结果直接打印出来


>>> os.system('ls')
04101419778.CHM   bash      document    media      py-django   video
11.wmv            books     downloads   Pictures  python
all-20061022      Desktop   Examples    project    tools

(2) os.popen

该方法不但执行命令还返回执行后的信息对象


popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.

例如:


>>>tmp = os.popen('ls *.py').readlines()
>>>tmp
Out[21]:
['dump_db_pickle.py ',
'dump_db_pickle_recs.py ',
'dump_db_shelve.py ',
'initdata.py ',
'__init__.py ',
'make_db_pickle.py ',
'make_db_pickle_recs.py ',
'make_db_shelve.py ',
'peopleinteract_query.py ',
'reader.py ',
'testargv.py ',
'teststreams.py ',
'update_db_pickle.py ',
'writer.py ']


好处在于:将返回的结果赋于一变量,便于程序的处理。

(3)  使用模块 subprocess


>>> import subprocess
>>> subprocess.call(["cmd", "arg1", "arg2"],shell=True)


获取返回和输出:


import subprocess
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
    print line,
retval = p.wait()

(4)  使用模块 commands


>>> import commands
>>> dir(commands)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'getoutput', 'getstatus','getstatusoutput', 'mk2arg', 'mkarg']
>>> commands.getoutput("date")
'Wed Jun 10 19:39:57 CST 2009'
>>>
>>> commands.getstatusoutput("date")
(0, 'Wed Jun 10 19:40:41 CST 2009')

注意: 当执行命令的参数或者返回中包含了中文文字,那么建议使用subprocess,如果使用os.popen则会出现下面的错误:


Traceback (most recent call last):
  File "./test1.py", line 56, inmain()
  File "./test1.py", line 45, in main
    fax.sendFax()
  File "./mailfax/Fax.py", line 13, in sendFax
    os.popen(cmd)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 46-52: ordinal not inrange(128)

标签:Python,Linux,系统命令
0
投稿

猜你喜欢

  • Python:format格式化字符串详解

    2021-02-11 19:23:58
  • php利用cookies实现购物车的方法

    2023-07-23 08:32:37
  • Python二维列表的创建、转换以及访问详解

    2022-08-09 16:03:15
  • Django admin管理工具TabularInline类用法详解

    2021-05-10 16:16:26
  • Python获取时间戳代码实例

    2023-11-13 04:02:52
  • 详解scrapy内置中间件的顺序

    2023-10-22 07:13:38
  • 常用的javascript设计模式

    2023-08-18 06:54:27
  • Java实现数据库连接的最详细教程分享

    2024-01-28 01:34:15
  • Python爬虫实现热门电影信息采集

    2023-02-08 22:51:28
  • 微信小程序实现日期格式化

    2023-07-20 20:28:32
  • SQLServer日期函数总结案例详解

    2024-01-13 07:50:49
  • MySQL 5.7.14 net start mysql 服务无法启动-“NET HELPMSG 3534” 的奇怪问题

    2024-01-12 17:19:38
  • MySQL 请选择合适的列

    2024-01-23 05:33:31
  • Pytorch中实现CPU和GPU之间的切换的两种方法

    2021-08-21 07:24:18
  • Python使用Django实现博客系统完整版

    2021-02-10 14:43:48
  • Python实现破解网站登录密码(带token验证)

    2021-09-29 06:22:22
  • 举例讲解Linux系统下Python调用系统Shell的方法

    2023-08-25 00:04:46
  • 使用python实现对元素的长截图功能

    2023-11-20 10:27:44
  • python的endswith()的使用方法及实例

    2023-04-30 04:42:11
  • 如何将Python编译成C语言

    2022-01-02 10:49:31
  • asp之家 网络编程 m.aspxhome.com