Python 检查check_call命令的stderr并基于
我确信有更好的方法来编写下面的代码…下面是我在当前代码中遇到的问题,请提供您可能有的任何输入Python 检查check_call命令的stderr并基于,python,python-2.7,Python,Python 2.7,我确信有更好的方法来编写下面的代码…下面是我在当前代码中遇到的问题,请提供您可能有的任何输入 我想检查下面命令的stderr,并根据错误消息重新运行它 Error mesage看起来像“Error:无法删除您当前所在的“字母数字字符串”分支,我正在尝试如下匹配,但遇到错误 import subprocess def main(): change="205739" proc = subprocess.Popen(['git', 'branch', '-d', change], stderr
import subprocess
def main():
change="205739"
proc = subprocess.Popen(['git', 'branch', '-d', change], stderr=subprocess.PIPE)
out, error = proc.communicate()
if error.startswith("error: Cannot delete the branch"):
subprocess.check_call(['git', 'branch', '-d', change])
if __name__ == '__main__':
main()
您确实希望避免使用
shell=True
,而是将其拆分为一个列表,这样您就不必使用插值来引导
若要测试是否相等,请使用=
;=
仅用于赋值,这在if
语句中是不允许的
如果要检查stderr
输出,需要使用.Popen()
:
import subprocess
def main():
change="205739"
proc = subprocess.Popen(['git', 'branch', '-d', change], stderr=subprocess.PIPE)
out, error = proc.communicate()
if error.startswith("error: Cannot delete the branch"):
subprocess.check_call(['git', 'branch', '-d', change])
您希望
==
测试相等性。使用shell=True有什么问题。我使用check\u调用的原因也是我可以捕获stderr并基于它执行一些操作…您建议使用open而不是check\u调用吗?@user1934146:请参阅为什么使用shell=True
不是一个好主意。stderr
参数check\u-call
的t不接受变量作为输入;它要么是PIPE
,一个文件对象,要么是stderr
,STDOUT
,但在使用check\u-call
时,使用PIPE
无法真正访问返回值。您提供的代码出现编译错误,TypeError:bufsize必须为一个整数,你能编译它吗?我注意到并修复了它,但之后出现了一个错误,TypeError:bufsize必须是一个整数,我用it@user1934146:您的代码不是我答案的正确副本。第一个参数是一个列表,只是'git'
。