以上就是给各位分享Python-第二次遍历文件不起作用,其中也会对python遍历次数进行解释,同时本文还将给你拓展Pygame按键在Jupyter实验室的第二次运行单元格中不起作用、pythonwa
以上就是给各位分享Python-第二次遍历文件不起作用,其中也会对python遍历次数进行解释,同时本文还将给你拓展Pygame 按键在 Jupyter 实验室的第二次运行单元格中不起作用、python walk 遍历文件夹、python – Cython中的并行性不起作用、python – Ghost不起作用等相关知识,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
本文目录一览:- Python-第二次遍历文件不起作用(python遍历次数)
- Pygame 按键在 Jupyter 实验室的第二次运行单元格中不起作用
- python walk 遍历文件夹
- python – Cython中的并行性不起作用
- python – Ghost不起作用
Python-第二次遍历文件不起作用(python遍历次数)
我对文件进行迭代有问题。这是我在解释器上键入的内容和结果:
>>> f = open(''baby1990.html'', ''rU'')>>> for line in f.readlines():... print(line)... # ... all the lines from the file appear here ...
当我尝试再次遍历同一个打开的文件时,我什么也没得到!
>>> for line in f.readlines():... print(line)... >>>
根本没有输出。为了解决这个问题,我必须对close()
文件进行编辑,然后再次将其打开以进行读取!那是正常行为吗?
答案1
小编典典是的,这是正常行为。基本上,你是第一次读取文件的末尾(可以像读取磁带一样对它进行图片处理),因此除非你使用f.seek(0)
重定位到文件开头的位置进行重置,否则你将无法从文件中读取更多内容。文件,或者将其关闭,然后再次打开,它将从文件的开头开始。
如果你愿意,可以改用with
语法,它将自动为你关闭文件。
例如,
with open(''baby1990.html'', ''rU'') as f: for line in f: print line
一旦完成该块的执行,文件将自动为你关闭,因此你可以重复执行此块,而无需自己显式关闭文件并以此方式再次读取文件。
Pygame 按键在 Jupyter 实验室的第二次运行单元格中不起作用
如何解决Pygame 按键在 Jupyter 实验室的第二次运行单元格中不起作用?
当我在 Jupyter Lab 中的内核重新启动后运行下面的代码时,如果我按下空格键,将产生一个突出显示的 ''aaa''
(应该如此)。
但是,如果我不得不再次重新运行同一个单元格(没有重新启动内核),击中空格键只会导致 Jupyter Lab 向下滚动并被 pygame
忽略,尽管程序在所有其他方面仍在运作
关于每次在 Jupyter 实验室运行该单元时如何让按键工作的任何想法?
谢谢
offset = 2130
#!/usr/bin/env python3
import argparse
import os
import queue
import sounddevice as sd
import vosk
import sys
import ast
import time
import colored
import pygame
start = time.time()
pygame.init()
q = queue.Queue()
def int_or_str(text):
"""Helper function for argument parsing."""
try:
return int(text)
except ValueError:
return text
def callback(indata,frames,time,status):
"""This is called (from a separate thread) for each audio block."""
if status:
print(status,file=sys.stderr)
q.put(bytes(indata))
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(
''-l'',''--list-devices'',action=''store_true'',help=''show list of audio devices and exit'')
args,remaining = parser.parse_kNown_args()
if args.list_devices:
print(sd.query_devices())
parser.exit(0)
parser = argparse.ArgumentParser(
description=__doc__,formatter_class=argparse.RawDescriptionHelpformatter,parents=[parser])
parser.add_argument(
''-f'',''--filename'',type=str,Metavar=''FILENAME'',help=''audio file to store recording to'')
parser.add_argument(
''-m'',''--model'',Metavar=''MODEL_PATH'',help=''Path to the model'')
parser.add_argument(
''-d'',''--device'',type=int_or_str,help=''input device (numeric ID or substring)'')
parser.add_argument(
''-r'',''--samplerate'',type=int,help=''sampling rate'')
args = parser.parse_args(remaining)
try:
if args.model is None:
args.model = "model"
if not os.path.exists(args.model):
print ("Please download a model for your language from https://alphacephei.com/vosk/models")
print ("and unpack as ''model'' in the current folder.")
parser.exit(0)
if args.samplerate is None:
device_info = sd.query_devices(args.device,''input'')
# soundfile expects an int,sounddevice provides a float:
args.samplerate = int(device_info[''default_samplerate''])
model = vosk.Model(args.model)
if args.filename:
dump_fn = open(args.filename,"wb")
else:
dump_fn = None
with sd.RawInputStream(samplerate=args.samplerate,blocksize = 8000,device=args.device,dtype=''int16'',channels=1,callback=callback):
print(''#'' * 80)
print(''Press Ctrl+C to stop the recording'')
print(''#'' * 80)
print(f''offset = {offset}'')
rec = vosk.KaldiRecognizer(model,args.samplerate)
xxx = True
while xxx==True:
data = q.get()
if rec.AcceptWaveform(data):
yag = rec.Result()
yag3 = ast.literal_eval(yag)
sec = time.time()-start + offset
ty_res = time.gmtime(sec)
res = time.strftime("%H:%M:%s",ty_res)
try:
print(f"{res} - {yag3[''text'']}")
except:
print(f"{res} - oops")
else:
pass
if dump_fn is not None:
dump_fn.write(data)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
print(''\nDone'')
xxx = False
# parser.exit(0)
pygame.quit()
if event.key == pygame.K_SPACE:
print(f"{colored.bg(226)} aaa {colored.bg(231)} ")
except KeyboardInterrupt:
print(''\nDone'')
pygame.quit()
parser.exit(0)
except Exception as e:
parser.exit(type(e).__name__ + '': '' + str(e))
pygame.quit()
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
python walk 遍历文件夹
g = os.walk(list_path)
img_files = [''%s\\%s'' % (i[0], j) for i in g for j in i[-1] if
j.endswith(''jpg'') or j.endswith(''png'')or j.endswith(''jpeg'') ]
python – Cython中的并行性不起作用
from cython import parallel from libc.stdio cimport printf def test_func(): cdef int thread_id = -1 with nogil,parallel.parallel(num_threads=10): thread_id = parallel.threadid() printf("Thread ID: %d\n",thread_id)
但是,它始终只启动一个线程,即始终只输出
Thread ID: 0
我在做多线程时做错了什么?
解决方法
要启用OpenMP,编译器将需要在编译和链接时传递一个额外的标志,否则将忽略代码的并行部分.
一些流行的编译器的标志如下:
> GCC = -fopenmp
> MSVC = / openmp
> icc = -openmp
假设您已将函数保存在test.pyx文件中,则在使用GCC时,以下setup.py应该可以正常工作.
from distutils.core import setup,Extension from Cython.Build import cythonize extensions = [Extension( "test",sources=["test.pyx"],extra_compile_args=["-fopenmp"],extra_link_args=["-fopenmp"] )] setup( ext_modules = cythonize(extensions) )
一旦这样编译,代码应该在运行时产生10个线程:
In [1]: import test In [2]: test.test_func() Thread ID: 9 Thread ID: 1 Thread ID: 6 Thread ID: 7 Thread ID: 3 Thread ID: 8 Thread ID: 5 Thread ID: 4 Thread ID: 0 Thread ID: 2
如果你想在cython docs中获得比this页面更多的信息,那么如何使用cython的并行性有一个很好的基本指南.
python – Ghost不起作用
from ghost import Ghost ghost = Ghost() page,resources = ghost.open(''http://google.com'')
这是一个非常简单的例子,这是追溯:
AttributeError: ''Ghost'' object has no attribute ''open''
我正在使用Python 2.7,我已经为64位安装了PySide 1.2.4而且我在使用Windows7的机器上工作
编辑:
我试过这个:
import ghost g = ghost.Ghost() with g.start() as session: page,extra_resources = session.open("http://www.google.es") print page.http_status
现在回溯是:
AttributeError:’nonetype’对象没有属性’http_status’但是如果我使用相同的代码而没有
print page.http_status
它没有显示错误
EDIT2:
Martijn Pieters给了我这个可能的解决方案:
from ghost import Ghost,Session ghost = Ghost() ghost = Session(ghost) ghost.open(''http://www.google.com'') ghost.capture_to(''screen_shot.png'')
此代码有效,但屏幕截图为空,对象具有“无”类型
解决方法
from ghost import Ghost ghost = Ghost() with ghost.start() as session: page,extra_resources = session.open("http://www.google.de") session.set_viewport_size(1920,1080) session.capture_to(''test.png'') ~
〜
关于Python-第二次遍历文件不起作用和python遍历次数的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于Pygame 按键在 Jupyter 实验室的第二次运行单元格中不起作用、python walk 遍历文件夹、python – Cython中的并行性不起作用、python – Ghost不起作用的相关知识,请在本站寻找。
本文标签: