相关疑难解决方法(0)

在Python 3.0中可以看到generator.next()吗?

我有一个生成系列的生成器,例如:

def triangleNums():
    '''generate series of triangle numbers'''
    tn = 0
    counter = 1
    while(True):
        tn = tn + counter
        yield tn
        counter = counter + 1
Run Code Online (Sandbox Code Playgroud)

在python 2.6中,我可以进行以下调用:

g = triangleNums() # get the generator
g.next()           # get next val
Run Code Online (Sandbox Code Playgroud)

但是在3.0中,如果我执行相同的两行代码,我会收到以下错误:

AttributeError: 'generator' object has no attribute 'next'
Run Code Online (Sandbox Code Playgroud)

但是,循环迭代器语法在3.0中有效

for n in triangleNums():
    if not exitCond:
       doSomething...
Run Code Online (Sandbox Code Playgroud)

我还没有能找到解释3.0行为差异的任何东西.

python iteration python-3.x

226
推荐指数
3
解决办法
11万
查看次数

如何编辑打印到stdout的字符串?

如何编辑刚打印的字符串?例如,对于倒数计数器(首先打印30,然后将其更改为29,依此类推)

谢谢.

python printing

7
推荐指数
1
解决办法
2140
查看次数

异步进度旋转器

这是进度旋转器的代码:

import sys
import time

def spinning_cursor():
    while True:
        for cursor in '|/-\\':
            yield cursor

spinner = spinning_cursor()
for _ in range(50):
    sys.stdout.write(spinner.next())
    sys.stdout.flush()
    time.sleep(10)
    sys.stdout.write('\b')
Run Code Online (Sandbox Code Playgroud)

输出

python2.7 test.py
|
Run Code Online (Sandbox Code Playgroud)

由于循环休眠了 10 秒,它的旋转速度非常慢......

如何在进程休眠时继续旋转旋转器?

python progress

3
推荐指数
1
解决办法
6486
查看次数

Python中的多线程curses输出

我正在尝试在长期运行的函数的进度条下方实现一个简单的微调器(使用根据此答案改编的代码)。

[########         ] x%
/ Compressing filename
Run Code Online (Sandbox Code Playgroud)

我让压缩和进度条在脚本的主线程中运行,而旋转器在另一个线程中运行,因此它实际上可以在压缩发生时旋转。但是,我curses同时使用进度条和微调器,并且都使用curses.refresh()

有时终端会随机输出乱码,我不知道为什么。我认为这是由于旋转器的多线程性质造成的,因为当我禁用旋转器时,问题就消失了。

这是旋转器的伪代码:

def start(self):
  self.busy = True
  global stdscr 
  stdscr = curses.initscr()
  curses.noecho()
  curses.cbreak()
  threading.Thread(target=self.spinner_task).start()

def spinner_task(self):
  while self.busy:
    stdscr.addstr(1, 0, next(self.spinner_generator))
    time.sleep(self.delay)
    stdscr.refresh()
Run Code Online (Sandbox Code Playgroud)

这是进度条的伪代码:

progress_bar = "\r[{}] {:.0f}%".format("#" * block + " " * (bar_length - block), round(progress * 100, 0))
progress_file = " {} {}".format(s, filename)
stdscr.clrtoeol()
stdscr.addstr(1, 1, "                                                              ")
stdscr.clrtoeol()
stdscr.addstr(0, 0, progress_bar)
stdscr.addstr(1, 1, progress_file)
stdscr.refresh()
Run Code Online (Sandbox Code Playgroud)

并从类似的地方打电话main()

spinner.start()
for each file: …
Run Code Online (Sandbox Code Playgroud)

python curses multithreading

3
推荐指数
1
解决办法
3130
查看次数