The format string passed to bytes.__format__ is not supported and resulted in a TypeError

Hey there, I'm currently working on formatting an sqlite file for better readability using the python script from dionea honeynet. However, each time I run the script, I keep running into this error:

File "./readlogsqltree.py", line 268, in print_logins
    login['login_password']))

TypeError: unsupported format string passed to bytes.__format__

In this case, the login['login_password'] is a variable retrieved from a select statement. Below is the specific function that is causing the issue:

def print_logins(cursor, connection, indent):
    r = cursor.execute("""
        SELECT 
            login_username,
            login_password
        FROM 
            logins
        WHERE connection = ?""", (connection, ))
    logins = resolve_result(r)
    for login in logins:
        print("{:s} login - user:'{:s}' password:'{:s}'".format(
            ' ' * indent,
            login['login_username'],
            login['login_password']))

Here's the resolution result function being referenced:

def resolve_result(resultcursor):
    names = [resultcursor.description[x][0] for x in range(len(resultcursor.description))]
    resolvedresult = [ dict(zip(names, i)) for i in resultcursor]
    return resolvedresult

Now, moving on to the Cursor section:

def print_db(opts, args):
    dbpath = 'logsql.sqlite'
    if len(args) >= 1:
        dbpath = args[0]
    print("using database located at {0}".format(dbpath))
    dbh = sqlite3.connect(dbpath)
    cursor = dbh.cursor()

Answer №1

While in the process of converting some Python 2 scripts to Python 3, I encountered the following error:

  File "/home/user/Documents/projects/tf-booking/tensorflow-object-detection-example/object_detection_app/app.py", line 152, in encode_image
    base64.b64encode(image_buffer.getvalue()))
TypeError: unsupported format string passed to bytes.__format__

The solution was to change

base64.b64encode(image_buffer.getvalue())
to
base64.b64encode(image_buffer.getvalue()).decode()
, as discussed in this post.

Answer №2

To work with Python 3, ensure you decode the string using decode('utf-8') prior to utilizing format()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty with implementing make_scorer in scikit-learn

Currently, I am working on implementing a classification algorithm using a dataset related to medicinal research. My main focus is to achieve good recall in disease recognition. In order to do so, I had the idea of creating a scorer like the following: re ...

Establish the xmethods for the C++ STL in GDB

I'm having trouble getting xmethods to work properly after following the instructions in this specific answer. Despite executing enable xmethod, when I run info xmethod I get no information showing up: (gdb) enable xmethod (gdb) info xmethod (gdb) Is ...

Determining the sunrise and sunset times based on a datetime index using the ephem library in Python

My challenge involves working with a daily time series that has a DateTime index. I am aiming to compute the specific sunrise and sunset times for each day within the DataFrame. The desired output will appear in columns named rise and set. In my approach, ...

determines the highest value in a column for a specific date

Is it possible to find the maximum sum column value for the date "2018 Jan" and return columns A, a, b, c with just one concise line of code? Date A sum a b c d 0 2018-01-19 user1 1.82 -0.2 ...

Retrieve the highest quality image by reading the JSON file from Last.FM

Currently, I am in the process of developing a project that will automatically send a Discord message on specific dates, such as 'Mon 22:00:00'. This message will contain details about my most listened-to album for that week. The code is function ...

What is the best way to extract JSON data from an HTML file and store it into a Python

My goal is to extract structured data from a JSON statement embedded in an HTML page. To achieve this, I extracted the HTML content and obtained the JSON using XPath: json.loads(response.xpath('//*[@id="product"]/script[2]/text()').extract_first ...

Python: Building Palindrome Integers

This particular challenge is intended for codewars: Task: Given an input n, determine the count of numbers less than n that are palindromic and can be expressed as the sum of consecutive squares. My approach involved computing the square of increasing nu ...

Tips for transforming a pandas dataframe into a dictionary that can be sliced

My pandas data frame df is structured as follows: import pandas as pd data = [[1, 'Jack', 'A'], [1, 'Jamie', 'A'], [1, 'Mo', 'B'], [1, 'Tammy', 'A'], [2, 'JJ', ' ...

Error: Unable to import the specified name 'string_int_label_map_pb2'

After running the compilation command below, the files were successfully compiled into .py files. protoc object_detection/protos/*.proto --python_out=. Despite this success, an error code was encountered: ~/Documents/imgmlreport/inception/classification ...

Encountering a type error when attempting to open a SQL file that has been

I'm currently working on a Python application using Django where users can upload SQL files. I am using fileField to receive the uploaded file, however, it is not being stored anywhere. When attempting to process the file by opening it, I encounter an ...

Adding JSON arrays into a MySQL table with Python

I am currently facing issues with inserting values into a MySQL table called "section". This table consists of 5 columns, including one integer, one text, and three JSON arrays. The JSON array values are stored in variables 's', 'l', an ...

What are the steps to start running the while loop?

To provide more clarity: I am developing an intersection control system for cars where each car must register its address in a shared list (intersectionList) if it intends to cross the intersection. If cars are on road piece 20 or 23, they add their addre ...

analyzing a snippet of HTML script using BeautifulSoup

As I attempt to gather data from a particular website, I have successfully identified the exact location of the required information. When inspecting the site in Chrome, I can see the specific data I need - in this case, the time. Here is an example of how ...

Troubleshooting error code 400 in Flask when processing request.json

I'm currently facing an issue with properly formatting a response using Flask.requests.json @app.route("/slack/post", methods=["POST"]) def post_response_to_slack(): try: body = request.json The output when using request.data is: b' ...

Combining multiple repositories using docker-compose

Currently, I have two services deployed on separate GitLab repositories but running on the same host using supervisord. The CI/CD process in each repository pushes code to this shared host. I am now looking to transition from supervisord to Docker. To beg ...

What is the reason for the absence of a call event when a code block is

Utilizing Python's sys.settrace method to track code execution for a program analysis project. The official documentation suggests that call events should be triggered when entering a code block, but I am not observing this behavior. Below is an exa ...

Can we enhance the optimization of curve fitting when one variable depends on another?

Is it feasible to perform curve fitting on a dual exponential function where one parameter is strictly greater than another? I'm unsure of how to enforce this constraint in my code. Below is a simple example: import numpy as np import matplotlib.pyp ...

Provide input to a currently active webdriver

Currently, I am in the process of using Pytest to create an automation script utilizing a Selenium Chrome driver. As someone who is relatively new to coding, there are certain aspects that I am struggling to automate efficiently; hence, I am exploring alte ...

Python Column Deletion

I need assistance removing the final two columns from my data frame using Python. The problem lies in the presence of cells with unnecessary values in the last two columns, which do not have headers. Below is the code I have attempted to use. However, as ...

Python Scrapy | Techniques for transferring the response data to the main function within the spider

I have been searching extensively for a solution using various search engines, but I may not be entering the correct keywords. Although I am aware that I can use the shell to manipulate CSS and XPath selectors right away, I am curious to know if it is poss ...