从python调用shell命令

时间:2012-12-27 21:11:13

标签: python shell unix

我有一个等效的shell命令(如下所示),我试图在一个python脚本中运行“as-is”,在linux机器上使用call命令并运行编译错误,除了调用之外还有更好的方法吗?辜负这个命令?我哪里错了?

from subprocess import call

def main ():

#ssh -p 29418 company.com gerrit query --commit-message --files --current-patch-set status:open project:platform/vendor/company-proprietary/wlan branch:master |grep refs| awk -F ' ' {'print $2'} |tee refspecs.txt
    call (["ssh -p 29418 company.com gerrit query", "--commit-message", "--files", "--current-patch-set", "status:open project:platform/vendor/company-proprietary/wlan branch:master","|grep refs| awk -F ' ' {'print $2'} |tee refspecs.txt")]

if __name__ == '__main__':
    main()

4 个答案:

答案 0 :(得分:2)

您需要拆分"ssh -p 29418 company.com gerrit query"(手动执行此操作,而不是使用.split()等。)

现在,您对subprocess.call()的调用会尝试执行整个字符串,显然您的PATH中没有该名称。

答案 1 :(得分:2)

由于您正在设置一个非常严重的管道,最简单的方法是使用shell执行命令。另外,请考虑使用check_call,以便了解是否存在问题。当然,最后的)]应该是])来修复编译错误:

from subprocess import check_call

def main ():
    check_call("ssh -p 29418 company.com gerrit query --commit-message --files --current-patch-set status:open project:platform/vendor/company-proprietary/wlan branch:master | grep refs | awk -F ' ' {'print $2'} | tee refspecs.txt", shell=True)

if __name__ == '__main__':
    main()

答案 2 :(得分:1)

from subprocess import check_call

with open("refspecs.txt", "wb") as file:
    check_call("ssh -p 29418 company.com "
        "gerrit query --commit-message --files --current-patch-set "
        "status:open project:platform/vendor/company-proprietary/wlan branch:master |"
        "grep refs |"
        "awk -F ' ' '{print $2}'",
               shell=True,   # need shell due to the pipes
               stdout=file)  # redirect to a file

我已删除tee以取消stdout。

注意:部分甚至整个命令都可以用Python实现。

答案 3 :(得分:0)

你有错误的顺序来关闭通话。

call (["ssh -p 29418 company.com gerrit query", "--commit-message", "--files", "--current-patch-set", "status:open project:platform/vendor/company-proprietary/wlan branch:master","|grep refs| awk -F ' ' {'print $2'} |tee refspecs.txt"])