学习啦>学习电脑>电脑安全>系统安全>

Python怎么运行系统命令行

时间: 黎正888 分享

  大家知道Python怎么运行系统命令行吗?下面就让学习啦小编教大家Python怎么运行系统命令行吧。

  Python运行系统命令行的方法

  一、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

  二、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 ']

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

  三、使用模块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()

  四、使用模块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, in

  main()

  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 no

Python怎么运行系统命令行相关文章:

1.Python怎么运行系统命令

2.C语言怎么调用系统命令行

3.Python怎么使用系统命令

4.Python怎么调用系统命令

5.Python怎么执行系统命令

Python怎么运行系统命令行

大家知道Python怎么运行系统命令行吗?下面就让学习啦小编教大家Python怎么运行系统命令行吧。 Python运行系统命令行的方法 一、os.system # 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息 system(command) - exit_stat
推荐度:
点击下载文档文档为doc格式

精选文章

  • xp系统怎么运行命令提示符
    xp系统怎么运行命令提示符

    在window系统中打开window提示符是一件经常想要操作的事情,下面就让学习啦小编教大家xp系统怎么运行命令提示符吧。 xp系统运行命令提示符的方法 1、打开

  • cmd命令修复系统
    cmd命令修复系统

    还原系统会遇到的不稳定,其实并不需要这么麻烦的,我们可以通过cmd命令的方法来快速检查并及时修复系统的。下面就让学习啦小编教大家cmd命令怎么修

  • Windows Vista怎么用命令行来还原系统
    Windows Vista怎么用命令行来还原系统

    Windows Vista系统中系统还原的方式很多,下面就让学习啦小编教大家用命令行来还原系统吧。 Windows Vista用命令行还原系统的方法 在系统开始启动时按F8键。

  • 怎么用命令行来卸载系统更新
    怎么用命令行来卸载系统更新

    相比从控制面板卸载系统更新,使用命令行卸载更新具有执行速度更快,更为稳定和可靠,适用范围更广等优点。甚至,在某些极端情况下,比如说控制面

1859835