Skip to main content
 首页 » 编程设计

python之在 python 中使用 subprocess.Popen 运行 git 命令

2025年05月04日13txw1958

我正在编写一个小的 python 脚本,需要从给定目录中执行 git 命令

代码如下:

import subprocess, os 
 
pr = subprocess.Popen(['/usr/bin/git', 'status'],                   
       cwd=os.path.dirname('/path/to/dir/'),  
       stdout=subprocess.PIPE,  
       stderr=subprocess.PIPE,  
       shell=True) 
(out, error) = pr.communicate() 
print out 

但它显示 git 用法作为输出。

如果命令不涉及 git,例如。 ['ls'] 然后它显示正确的输出。

有什么我想念的吗?

python 版本 - 2.6.6

谢谢。

请您参考如下方法:

subprocess.Popen :

On Unix, with shell=True: […] If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.

您不需要 shell=True 和参数列表。设置 shell=False。