python小菜 2008-09-18 01:35 采纳率: 0%
浏览 531
已采纳

在 Python 中调用外部命令

How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?

转载于:https://stackoverflow.com/questions/89228/calling-an-external-command-in-python

  • 写回答

12条回答 默认 最新

  • 程序go 2008-09-18 01:39
    关注

    Look at the subprocess module in the standard library:

    from subprocess import call
    call(["ls", "-l"])
    

    The advantage of subprocess vs. system is that it is more flexible (you can get the stdout, stderr, the "real" status code, better error handling, etc...).

    The official documentation recommends the subprocess module over the alternative os.system():

    The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function [os.system()].

    The "Replacing Older Functions with the subprocess Module" section in the subprocess documentation may have some helpful recipes.

    Official documentation on the subprocess module:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(11条)

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型