标签: python-3.9

我正在使用 python 3.9,但我不知道如何在我的 Windows 10 中安装 pyaudio

当前使用 Visual Studio Code 尝试使用pip install pyaudio但它只是给出了一个错误,如:

PS C:\Users\NIKHIL> pip install pyaudio
Defaulting to user installation because normal site-packages is 
not writeable
Collecting pyaudio
  Using cached PyAudio-0.2.11.tar.gz (37 kB)
Building wheels for collected packages: pyaudio
  Building wheel for pyaudio (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: 'c:\program files\python39\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\NIKHIL\\AppData\\Local\\Temp\\pip-install-yo0mmwlt\\pyaudio_d4ca14ee2a5246debede93cab086f909\\setup.py'"'"'; __file__='"'"'C:\\Users\\NIKHIL\\AppData\\Local\\Temp\\pip-install-yo0mmwlt\\pyaudio_d4ca14ee2a5246debede93cab086f909\\setup.py'"'"';f=getattr(tokenize, 
'"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\NIKHIL\AppData\Local\Temp\pip-wheel-cbxwzcr9'
       cwd: C:\Users\NIKHIL\AppData\Local\Temp\pip-install-yo0mmwlt\pyaudio_d4ca14ee2a5246debede93cab086f909\
  Complete output (9 lines):
  running …
Run Code Online (Sandbox Code Playgroud)

python pyaudio python-3.9

2
推荐指数
1
解决办法
8255
查看次数

将 pandas 数据帧导出到 xlsx:处理 python 3.9 上的 openpyxl 问题

使用最新的软件包版本:openpyxl:3.0.6 | 熊猫:1.2.3 |蟒蛇:3.9

在将上面的软件包更新到报告的最新版本之前,下面的功能运行良好。

现在它会引发错误:“zipfile.BadZipFile:文件不是 zip 文件”。

这样的功能确实很有用,并且很高兴知道它是否可以修复以使其正常工作。

下面的函数可以直接运行,只需将“pathExport”替换为您的导出目录进行测试即可。

    def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                           truncate_sheet=False, 
                           **to_excel_kwargs):
        """
        Append a DataFrame [df] to existing Excel file [filename]
        into [sheet_name] Sheet.
        If [filename] doesn't exist, then this function will create it.
    
        Parameters:
          filename : File path or existing ExcelWriter
                     (Example: '/path/to/file.xlsx')
          df : dataframe to save to workbook
          sheet_name : Name of sheet which will contain DataFrame.
                       (default: 'Sheet1')
          startrow : upper left cell row to dump data frame.
                     Per default …
Run Code Online (Sandbox Code Playgroud)

xlsx pandas openpyxl python-3.9

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

2
推荐指数
1
解决办法
9万
查看次数

Python 3.10 中的 Tkinter?

我正在尝试在 Python 3.10 项目中使用 Tkinter。我已经使用 Python 3.10 创建了虚拟环境并安装了 Tkinter。当我运行时,import tkinter出现以下错误。

Traceback (most recent call last):
  File "/home/xxx/yyy/main.py", line 11, in <module>
    import tkinter
  File "/usr/local/lib/python3.10/tkinter/__init__.py", line 37, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ModuleNotFoundError: No module named '_tkinter'
Run Code Online (Sandbox Code Playgroud)

但是,如果我在使用 Python 3.9 的虚拟环境之外执行相同的操作,或者使用 Python 3.9 创建一个新的虚拟环境,则它可以正常运行,不会出现错误。

3.10 中是否还不支持 Tkinter,还是我可能做错了什么?

python tkinter python-3.x python-3.9 python-3.10

2
推荐指数
1
解决办法
1万
查看次数

具有固定 .keys() 内容和可变参数的 Python 字典

我正在尝试从文本文件中读取大量数据到字典中,并且我犯了几个小错别字,最终导致创建新的键/值对并破坏程序(这可能很烦人和痛苦)调试)。

这让我想知道是否有一种方法可以创建一个字典,在初始声明之后不能添加或删除任何键。我觉得这是必然存在的东西,但我找不到它的例子;有谁知道有什么符合要求的吗?

def change_key(dictionary, key, new_value):
    a = dictionary.__len__()
    dictionary[key] = new_value
    if dictionary.__len__() != a:
        raise ValueError("new key added")
Run Code Online (Sandbox Code Playgroud)

我正在寻找的是上面代码的更优雅的实现,即:

  1. 不是一大堆乱七八糟的代码

  2. 能够处理诸如附加到嵌套列表或添加到嵌套字典之类的事情

  3. 相当有效

python python-3.9

2
推荐指数
1
解决办法
755
查看次数

Python 3.9 - 如何打印和格式化 .txt 文件?

我将如何定义一个函数,以便在不更改文件内容的情况下以特定方式打印文本文件?或者也许有什么更有效的方法来解决这个问题?

文本文件:

menu.txt
Cheese Burger, 5.00
Chicken Burger, 4.50
Fries, 2.00
Onion Rings, 2.50
Drinks, 1.50
Run Code Online (Sandbox Code Playgroud)

期望的输出:

1.  Cheese Burger           5.00
2.  Chicken Burger          4.50        
3.  Fries                   2.00
4.  Onion Rings             2.50
5.  Drinks                  1.50
Run Code Online (Sandbox Code Playgroud)

python format text-files python-3.9

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

与 Union 元素不兼容的类型

我最近收到了这个很好的答案,用于以下方面:

from typing import Union, cast


class Default:
    """Placeholder for default arguments."""


# ham[] is mutable.  `None` has meaning (or is not preferred).
def spam(ham: Union[list[str], None, type[Default]] = Default):
    if ham is Default:
        ham = ['prosciutto', 'jamon']
    #ham = cast(Union[list[str], None], ham)
    #assert isinstance(ham, (list, type(None)))
    if ham is None:
        print('Eggs?')
    else:
        print(str(len(ham)) + ' ham(s).')
Run Code Online (Sandbox Code Playgroud)

mypy错误:

Failed (exit code: 1) (2655 ms)

main.py:17: error: Argument 1 to "len" has incompatible type "Union[List[str], Type[Default]]"; expected "Sized" …
Run Code Online (Sandbox Code Playgroud)

python type-hinting mypy python-typing python-3.9

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

cv2.VideoCapture(0, cv2.DSHOW) 返回无

我正在尝试使用 opencv 从笔记本电脑(或外部 USB 摄像头)上的内置网络摄像头捕获视频,特别是带有 DSHOW 参数的 VideoCapture。我知道有一种方法可以设置分辨率甚至 FPS,但是当我将其包含在代码中时, API 的 DirectShow 参数不会返回任何内容。

例如;

# returns my webcam's stream, but all optional arguments are ignored
camera = cv2.VideoCapture(0)
camera = cv2.VideoCapture(0, cv2.CAP_V4L2)

# returns none and loops infinitely or errors out when *if im.any()*
camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)
Run Code Online (Sandbox Code Playgroud)

这是上面之后的代码;

# should set resolution, settings are always ignored
camera.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)

while(True):
    retval, im = camera.read()
    if im.any(): # errors out when image is none
        cv2.imshow("image", im)

    k = …
Run Code Online (Sandbox Code Playgroud)

streaming opencv ubuntu-18.04 python-3.9

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

如何在日志消息中添加当前日期和时间前缀?

我正在使用 Python 3.9 和 Django 3.2。我在 settings.py 文件中配置了日志记录

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',
    },
}
Run Code Online (Sandbox Code Playgroud)

当我登录我的一门课程时,我会这样做

import logging
...
class TransactionService:
    def __init__(self):
        self._logger = logging.getLogger(__name__)


    def my_method(self, arg1, arg2):
            ...
        self._logger.info("Doing some logging here.")
      

  
Run Code Online (Sandbox Code Playgroud)

如何配置记录器,以便在打印消息时以当前日期和时间为前缀?

python django logging django-3.0 python-3.9

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

MacOSx 上的 python 3.9 从 3.7 中的多处理发生了变化,如何修复?

Python 3.9 多重处理似乎在整个文件上运行许多额外的循环,而 3.7 没有这样做。该机器有 8 个核心,因此有 8 个循环。我该如何解决。这不是我所期望的——线程模块是否也重新设计了,这个问题是否也发生在该模块中。这是代码:

 !/usr/bin/python
from   time            import strftime
import multiprocessing as mp

print (strftime("%H:%M:%S") + ' Run line5 ' )

def pullLast():  
    print(12345678998765432345678)
    return 1

def mprocULwork(uplist): # build a queue with tuple
    ULsyms = [e for e in uplist if e is not None] 
    p_size          = mp.cpu_count()
    pool            = mp.Pool(processes=p_size, maxtasksperchild=400,)
    pool_outputs    = pool.map(ULProcess, ULsyms)
    pool.close()    # no more tasks
    pool.join()     # wrap up current tasks
    del pool
    print (strftime("%H:%M:%S"), "Finished ULwork")

def …
Run Code Online (Sandbox Code Playgroud)

python multiprocessing python-3.9

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

Python 3.9 版本不支持 match 语句

我在一台新计算机上安装了 Python,不幸的是,我收到了一条来自我已经使用了一段时间的代码的错误消息。这是关于“匹配”声明的。这是代码:

import os

def save(df, filepath):
    dir, filename = os.path.split(filepath)
    os.makedirs(dir, exist_ok=True)
    _, ext = os.path.splitext(filename)
    match ext:
        case ".pkl":
            df.to_pickle(filepath)
        case ".csv":
            df.to_csv(filepath)
        case _:
            raise NotImplementedError(f"Saving as {ext}-files not implemented.")
Run Code Online (Sandbox Code Playgroud)

现在我的问题是,如何解决“Python版本3.9不支持匹配语句”的问题?

python python-3.9

1
推荐指数
1
解决办法
2万
查看次数

当我使用 PlaySound 时 Python 冻结

当我将 tkinter 与 Playsound 一起使用时,它会冻结直到播放声音。我尝试过使用 block = False 但它根本不播放声音!

这是我的代码的一部分:

from tkinter import *
from tkinter import ttk
from playsound import playsound


class GameMaker:
    def __init__(self,root=None):
        self.sounds={}
    def AddSound(self,name,directory,overide=False,times=0,TimesOveride=0):
        if times != 0:
            name = name + str(times)
        if TimesOveride != 0:
            if times >= 10:
                return None
        else:
            if times >= TimesOveride:
                return None
            
        try:
            self.sounds[name]
            if overide == True:
                self.sounds[name]=directory
            else:
                AddSound(name,directory,times=times+1)
        except:
            self.sounds[name]=directory
    def PlaySound(self,sound):
        playsound(self.sounds[sound],block=False)
    def MapAll(self,command):
        keys = list("qwertyuiopasdfghjklzxcvbnm")
        for key in keys:
            self.Bind(key,command)
            print(key) …
Run Code Online (Sandbox Code Playgroud)

tkinter python-3.9 python-playsound

0
推荐指数
1
解决办法
572
查看次数