当我运行下面的脚本时,我得到了以下错误,可以帮助确定问题是什么以及如何克服它
代码:-
import sys
import os
def main ():
to = ''
with open('caf_gerrits.txt','r') as f :
for gerrit in f :
print "Gerrit " + gerrit
cmd = "ssh -p 29418 review-android.company.com gerrit query --format=JSON --current-patch-set --commit-message --files \'%s\' >> gerrit_output.txt" %(gerrit)
os.system(cmd)
if __name__ == '__main__':
main()错误:-
Gerrit 530731
Traceback (most recent call last):
File "test.py", line 14, in <module>
cmd = "ssh -p 29418 review-android.company.com gerrit query --format=JSON --current-patch-set --commit-message --files \'%s\' >> gerrit_output.txt" %(gerrit)
File "test.py", line 10, in main
to = ''
TypeError: must be string without null bytes, not str发布于 2013-12-17 08:02:56
问题是转义后的单引号--我打赌是文件。没有必要对它们进行转义,因为您在外部使用了双引号。
使用'subprocess‘模块的替代解决方案如下所示。注意这是刚刚在这里输入的,我还没有运行它。应该很接近了。
def main ():
to = ''
ssh_command = ["ssh", "-p", 29418, "review-android.company.com", "gerrit",
"query", "--format", "JSON", "--current-patch-set",
"--commit-message", "--files", ]
with open('gerrit_output.txt', 'a') as fp:
with open('caf_gerrits.txt','r') as f :
for gerrit in f :
print "Gerrit " + gerrit
result = subprocess.check_output(ssh_command + [gerrit, ])
fp.write(result)
if __name__ == '__main__':
main()查看“subprocess”模块的文档,还有很多其他方法可以实现这一点。无论你选择哪种方式,你都会得到比简单的“os.system”调用更好的错误处理和输出捕获。
发布于 2013-12-17 07:20:09
尝试使用:
for gerrit in f.readlines():您正在尝试使用文件描述符而不是文件本身的内容进行迭代。
https://stackoverflow.com/questions/20622868
复制相似问题