我有一个用Python编写的程序,并在其中使用git命令.. 由于某些原因,我不想使用git-python或其他子进程。 但我目前陷入git clone
输出。如何在运行git命令时获得子进程标准输出?
我试过一些代码片段。一些工作正常,如ping 8.8.8.8
,但不是git clone
。
例如
使用线程
def log_worker(stdout):
while True:
last = non_block_read(stdout).strip()
if last != "":
print(last)
def non_block_read(output):
fd = output.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
try:
return output.read()
except:
return ''
def test():
mysql_process = subprocess.Popen(
"ping google.com",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
thread = Thread(target=log_worker, args=[mysql_process.stdout])
thread.daemon = True
thread.start()
mysql_process.wait()
thread.join(timeout=1)
test()
或
newlines = ['\n', '\r\n', '\r']
def unbuffered(proc, stream='stdout'):
stream = getattr(proc, stream)
with contextlib.closing(stream):
while True:
print('tt')
out = []
last = stream.read(1)
# Don't loop forever
if last == '' and proc.poll() is not None:
break
print('last', last)
while last not in newlines:
print("loop")
# Don't loop forever
if last == '' and proc.poll() is not None:
break
out.append(last)
last = stream.read(1)
out = ''.join(out)
yield out
def example():
cmd = ['ls', '-l', '/']
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
# Make all end-of-lines '\n'
universal_newlines=True,
shell = True
)
for line in unbuffered(proc):
print('new line')
print line
example()
和最常见的一种
for line in iter(proc.stdout.readline, ''):
sys.stdout.write('{:.2f} {}\n'.format(
time.time() - start,
line.rstrip()
))
sys.stdout.flush()
他们都工作正常ping google.com
名称,但n ot git clone
。 有什么办法可以解决这个问题吗? 在此先感谢!
UPDATE1: 面对面,我只想得到git clone
的完成百分比。不需要日志或任何日志文件。
为什么是你使用'shell = True'(特别是因为你使用的是参数列表而不是shell命令行)? – abarnert 2014-09-23 03:50:47
不会subprocess.check_output是一件容易的事情吗? – 2014-09-23 03:52:31
另外,哪个单词是最常见的“最常见”?你什么时候需要日志式时间戳,但不想使用'logging'模块? – abarnert 2014-09-23 04:07:15