I have a Python script obtained from a project which I am trying to debug however I am unable to resolve one error. Per the author's description of the project, everything works fine.
The script takes a parameter called "ascii" which is of type str as shown below:
parser.add_argument('--ascii', type=str,
help='ASCII Data type: ASCII characters')
Per my understanding, in the following code, it processes the input string one character at a time and each character is sent to a function, iter_bin() which will take the ASCII value of the character and convert it to binary, appending the output to a list.
ASCIIDATA = args.ascii
dataArray = []
for line in ASCIIDATA:
for entry in line:
# Make sure everything is a number, convert if not
dataArray.append(''.join(s for s in iter_bin(entry)))
def iter_bin(s):
sb = s.encode('ascii')
return (format(b, '07b') for b in sb)
When I run this code, I get the following error:
Traceback (most recent call last):
File "check.py", line 107, in <module>
main()
File "check.py", line 70, in main
dataArray.append(''.join(s for s in iter_bin(entry)))
File "check.py", line 70, in <genexpr>
dataArray.append(''.join(s for s in iter_bin(entry)))
File "check.py", line 82, in <genexpr>
return (format(b, '07b') for b in sb)
ValueError: Unknown format code 'b' for object of type 'str'
How can I resolve this error?
Thanks.
Related
I am trying to make a program that translates whatever you say in Swedish and PyAutoGUI Typewrites it. But when I run the code, I just get the same error.
trans=Translator()
translating_text=input('Enter text to translate into S w e d i s h:')
t=trans.translate(translating_text,src='en',dest='sv')
time.sleep(5)
translated=t
pyautogui.typewrite(translated)
pyautogui.press('enter')
The error:
Traceback (most recent call last):
File "C:\Users\admin\Documents\Python Projects\CrendlePy.py", line 56, in <module>
ahm_swedish()
File "C:\Users\admin\Documents\Python Projects\CrendlePy.py", line 54, in ahm_swedish
pyautogui.typewrite(translated)
File "C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-
packages\pyautogui\__init__.py", line 586, in wrapper
returnVal = wrappedFunction(*args, **kwargs)
File "C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-
packages\pyautogui\__init__.py", line 1665, in typewrite
for c in message:
TypeError: 'Translated' object is not iterable
Can someone pls help me with this?
Error speaks for its self, pyautogui.typewrite() is expecting iterable, for example, string, but you are passing Translated object.
You have to explore the way to get text out of your Translated object and only then pass it to pyautogui.
have this Python script that is producing an error for some reason. The error is:
Traceback (most recent call last):
File "scraper2.py", line 79, in <module>
etree.SubElement(coinx, "trader", {'variable': coinx}).text = prices[coin]["trader"]
File "src/lxml/etree.pyx", line 3136, in lxml.etree.SubElement
File "src/lxml/apihelpers.pxi", line 199, in lxml.etree._makeSubElement
File "src/lxml/apihelpers.pxi", line 194, in lxml.etree._makeSubElement
File "src/lxml/apihelpers.pxi", line 323, in lxml.etree._initNodeAttributes
File "src/lxml/apihelpers.pxi", line 334, in lxml.etree._addAttributeToNode
File "src/lxml/apihelpers.pxi", line 1538, in lxml.etree._utf8
TypeError: Argument must be bytes or unicode, got '_Element'
The script causing this is:
root = etree.Element("root")
for coin in prices:
coinx=etree.Element("coin")
etree.SubElement(coinx, "trader", {'variable': coinx}).text = prices[coin]["trader"]
etree.SubElement(coinx, "metal").text = prices[coin]["metal"]
etree.SubElement(coinx, "type").text = prices[coin]["type"]
etree.SubElement(coinx, "price").text = prices[coin]["price"] # Needs scraper code to function correctly
root.append(coinx)
fName = 'data.xml'
with open(fName, 'wb') as f:
# remove encoding here, in case you want escaped ASCII characters: £
f.write(etree.tostring(root, xml_declaration=True, encoding="utf-8", pretty_print=True))
Script is designed to output information to an XML file (data.xml).
New to using the LXML python module and cannot seem to find out how to solve it. If someone could help me out then that would be great! Thanks!
The answer to your problem is in the initial part of your stacktrace:
etree.SubElement(coinx, "trader", {'variable': coinx}).text = prices[coin]["trader"]
You create a new element named trader, as a child of coinx.
The actual reason of failure is in {'variable': coinx}.
The third parameter of SubElement is attrib - a dictionary of attributes.
In this case you attempt to create a single attribute named variable, for now OK.
The problem is that the value of this attribute should be a string,
passed as either bytes or unicode.
But the value which you passed is coinx i.e. the parent element.
Probably you should pass some other content here.
I'm trying to add keywords to the IPTC data in a JPG file and failing miserably. I'm able to read in the keywords using the iptcinfo3 library and, seemingly, append the keyword to the list of current keywords but I'm failing when trying to write those keywords back to the JPG file, if not sooner. The error message is a bit unclear to me and may actually reference the appending of the new keyword (although a print statement seems to indicate it took).
I've tried three different metadata libraries (there doesn't seem to be one standard) and this is the furthest I've gotten with any of them (failing to even install one and not being able to get a second one to run). This seems so basic but I can't figure it out and haven't been able to adapt the few other code examples I've seen online to work, including iptcinfo3's example code fragment.
The current Error message is:
| => pipenv run python editMetadata.py
WARNING: problems with charset recognition (b'\x1b')
[b'Gus']
[b'Gus', b'frog']
Traceback (most recent call last):
File "editMetadata.py", line 22, in <module>
info.save_as('Gus2.jpg')
File "/Users/Scott/.local/share/virtualenvs/editPhotoMetadata-tx0JAOmI/lib/python3.7/site-packages/iptcinfo3.py", line 635, in save_as
jpeg_parts = jpeg_collect_file_parts(fh)
File "/Users/Scott/.local/share/virtualenvs/editPhotoMetadata-tx0JAOmI/lib/python3.7/site-packages/iptcinfo3.py", line 324, in jpeg_collect_file_parts
adobeParts = collect_adobe_parts(partdata)
File "/Users/Scott/.local/share/virtualenvs/editPhotoMetadata-tx0JAOmI/lib/python3.7/site-packages/iptcinfo3.py", line 433, in collect_adobe_parts
out = [''.join(out)]
TypeError: sequence item 0: expected str instance, bytes found
Code:
from iptcinfo3 import IPTCInfo
import os
# Create new info object
info = IPTCInfo('Gus.jpg')
# Print list of keywords
print(info['keywords'])
# Append the keyword I want to add
info['keywords'].append(b'frog')
# Print to test keyword has been added
print(info['keywords'])
# Save new info to file
info.save()
info.save_as('Gus2.jpg')
Instead of appending use equal "="
from iptcinfo3 import IPTCInfo
info = IPTCInfo('Gus.jpg')
print(info['keywords'])
# add keyword
info['keywords'] = ['new keyword']
info.save()
info.save_as('Gus_2.jpg')
I have the same error. It seems to be an issue with the save depending on the file.
from iptcinfo3 import IPTCInfo
info = IPTCInfo('image.jpg', force=True)
info.save()
Which gives me the same error.
WARNING: problems with charset recognition (b'\x1b')
WARNING: problems with charset recognition (b'\x1b')
Traceback (most recent call last):
File "./searchimages.py", line 123, in <module>
main(sys.argv[1:])
File "./searchimages.py", line 119, in main
find_photos(str(sys.argv[1]))
File "./searchimages.py", line 46, in find_photos
write_keywords(image, current_keywords, new_keywords)
File "./searchimages.py", line 109, in write_keywords
info.save_as('out.jpg')
File "/usr/local/lib/python3.7/site-packages/iptcinfo3.py", line 635, in save_as
jpeg_parts = jpeg_collect_file_parts(fh)
File "/usr/local/lib/python3.7/site-packages/iptcinfo3.py", line 324, in jpeg_collect_file_parts
adobeParts = collect_adobe_parts(partdata)
File "/usr/local/lib/python3.7/site-packages/iptcinfo3.py", line 433, in collect_adobe_parts
out = [''.join(out)]
TypeError: sequence item 0: expected str instance, bytes found
I run the script with python3 in the terminal but when I reach a certain point in it, I get the following error:
Traceback (most recent call last):
File "client.py", line 50, in <module>
client()
File "client.py", line 45, in client
s.send(bytes((msg, 'utf-8')))
TypeError: 'str' object cannot be interpreted as an integer
This is the code it refers to.
else :
# user entered a message
msg = sys.stdin.readline()
s.send(bytes((msg, 'utf-8')))
sys.stdout.write(bytes('[Me] '))
sys.stdout.flush()
I read the official documentation for bytes() and another source
https://docs.python.org/3.1/library/functions.html#bytes
http://www.pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/
but I am no closer to understanding how to fix this. I realise that my msg is a string and I need an integer, but I am confused about how to convert it. Can you please help me, or direct me to a source that will help me?
Edit 1: I changed the line
s.send(bytes((msg, 'utf-8')))
to
s.send(bytes(msg, 'utf-8'))
but now I get the following error:
Traceback (most recent call last):
File "client.py", line 50, in <module>
client()
File "client.py", line 46, in client
sys.stdout.write(bytes('[Me] '))
TypeError: string argument without an encoding
Edit 2: According to #falsetru updated answer.
Using bytes literal gives me
TypeError: must be str, not bytes
Change the following line:
s.send(bytes((msg, 'utf-8')))
as:
s.send(bytes(msg, 'utf-8'))
In other words, pass a string and an encoding name instead of a passing a tuple to bytes.
UPDATE accoridng to question change:
You need to pass a string to sys.stdout.write. Simply pass a string literal:
sys.stdout.write('[Me] ')
My program is giving me an error when it tries to convert a string from a list of strings to a floating point number. The list is read from a line in a CSV text file and then separated into a list. How do I make this work and why is it going wrong? Here are the relevant bits of code:
def Main():
srcf = open(bkp, 'r')
for line in srcf:
liLn = line.split(',')
...Then the following function is called...
def Pred_PSME(liLn):
dbh = float(liLn[6])
Here is the line from the file:
1345327,20486,"ABCO","Abies concolor","Y","Y","31.496","0.0779","19.3567",,"0.5602","0",1,"0.9268","11.8968","2.6832","6.6646","2399.256",54.47,24.15,248.47,42.19,9.16,8.16,9.23,272.27,264.11,369.30,345.15,71.80,0.00,0.00,4393.57,4106.22,3239.25,3142.07,854.30,0.00,0.00,,12.70,10.16,15.24,0.02,0.04,0.38,0.38,0.00,0.00,1.95,1.83,1.44,1.40
I get this error message:
Traceback (most recent call last):
File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 263, in <module>
Main()
File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 36, in Main
li_tBQI = BQI_Calc(liLn)
File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 63, in BQI_Calc
di_eqns = {"PSME": Pred_PSME(liLn), "ABAM":Pred_ABAM(liLn), \
File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 172, in Pred_PSME
dbh = float(liLn[6])
ValueError: could not convert string to float: "31.496"
I'm using Python 2.7 on an Ubuntu Linux computer.
You need to strip the double quotes off the string. This will then you give a legitimate floating point string that float() can convert.