【问题标题】:os.system command to call shell script with argumentsos.system 命令调用带有参数的 shell 脚本
【发布时间】:2013-09-01 04:48:39
【问题描述】:

我正在编写一个使用os.system 命令调用shell 脚本的python 脚本。我需要帮助了解如何将参数传递给shell 脚本?以下是我正在尝试的..但它不起作用。

os.system('./script.sh arg1 arg2 arg3')

我不想使用subprocess 来调用shell 脚本。任何帮助表示赞赏。

【问题讨论】:

  • 为什么不想使用子流程模块?
  • 二、为什么不使用子进程?
  • 另外,当你说它不起作用时,你怎么知道它不起作用?有错误信息吗?

标签: python shell arguments os.system


【解决方案1】:

将您的脚本和它的 args 放入一个字符串中,请参见下面的示例。

HTH

#!/usr/bin/env python

import os

arg3 = 'arg3'
cmd = '/bin/echo arg1 arg2 %s' % arg3

print 'running "%s"' % cmd

os.system(cmd)

【讨论】:

    【解决方案2】:

    如果您在 os.system (...) 之前插入以下行,您可能会看到您的问题。

    print './script.sh arg1 arg2 arg3'

    在开发这种类型的东西时,在实际尝试之前确保命令确实是您所期望的通常很有用。

    示例:

    def Cmd():
        return "something"
    
    print Cmd()
    

    当您满意时,注释掉print Cmd() 行并使用os.system (Cmd ()) 或子进程版本。

    【讨论】: