Python 运行命令时键入错误
我在运行下面的脚本时遇到以下错误,是否可以帮助确定问题是什么以及如何克服它 代码:-Python 运行命令时键入错误,python,Python,我在运行下面的脚本时遇到以下错误,是否可以帮助确定问题是什么以及如何克服它 代码:- 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.compan
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
Gerrit 530731
回溯(最近一次呼叫最后一次):
文件“test.py”,第14行,在
cmd=“ssh-p 29418 review-android.company.com gerrit query--format=JSON--current patch set--commit message--files\'%s\'>>gerrit_output.txt”%(gerrit)
文件“test.py”,第10行,在main中
至=“”
TypeError:必须是不带空字节的字符串,而不是str
尝试使用:
for gerrit in f.readlines():
您试图使用文件描述符而不是文件本身的内容进行迭代。问题在于--files之后的转义单引号。没有必要对它们进行转义,因为您在外部使用了双引号 使用“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()
查看“子流程”模块的文档,有很多其他方法可以实现这一点。与简单的“os.system”调用相比,您选择的任何方式都可以获得更好的错误处理和更好的输出捕获。您使用的是哪种版本的Python?我在CPython 2.7、Pypy 2.2或Jython 2.7b1中没有遇到此错误。我复制/粘贴并更改cmd,脚本工作正常。所以可能是你有一些东西没有显示在这里造成的问题。从错误消息中,第10行是to='',但我们在源代码中没有看到它。我们错过了什么吗?@PasteBT-我在使用pythong 2.7.3,你是否创建了一个文件caf_gerrits并在其中包含一些类似530731的数字列表?@user2955256是的,我错过了。@PasteBT-出于某种原因,我一直看到这个,您是否建议调试方法或任何其他方法来解决此问题?这可能与您使用的命令有关,我使用的是您使用的python的哪个版本?@PasteBT-am使用的是python 2.7。3@MattDmo-您的建议没有帮助使用Python2.7和3.x您可以在开放描述符上循环。顺便说一句,请查看“subprocess”模块。与简单地使用“os.system”相比,它有一些更好的特性。您能建议谁在这里使用子流程而不是os.system吗?