I am trying to create a Python program that will query a URL and produce a JSON file. I need to pass an argument in the end of the URL which comes from the SQL query.
I have imported the requests library.
I get an error message 'TypeError: float argument required, not str' when I am trying to pass argument in the URL.
There is only one column of result produced from the query:
id
2
3
4
Below is what I came up with:
import MySQLdb
import requests
con=MySQLdb.connect(host="localhost",user="test", passwd="test", db ="mfg")
cur = con.cursor()
select=("select id from tblMfg")
cur.execute(select)
result=cur.fetchall()
for i in result:
col =i[0]
col1=str(col)
url = 'http://appl.xyz.net:8080/app/content/pq/doQuery?solution=nd&path=&file=Test.nd&dataAccessId=1¶mid=%d' % col1
user = 'abc'
password ='testgo'
data = requests.get(url, auth=(user, password))
json_data=data.json()
print json_data
Leave creating parameters to the requests framework instead:
params = {'solution': 'nd', 'path': '', 'file': 'Test.nd', 'dataAccessId': '1',
'paramid': str(col[0])}
url = 'http://appl.xyz.net:8080/app/content/pq/doQuery'
user = 'abc'
password ='testgo'
data = requests.get(url, auth=(user, password), params=params)
The error message 'TypeError: float argument required, not str' also occurs when you try to format a string containing an (accidental) naked percent sign.
Example:
>>> print "fail 100% for serverid|%s| " % ("a")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: float argument required, not str
>>>
The "f" after the "100% " is interpreted as asking for a floating point argument, whereas it was simply my smudgefingers leaving off the second percent sign.
>>> print "fail 100%% for serverid|%s| " % ("a")
fail 100% for serverid|a|
>>>
works fine. If the word following the "100% " begins with d or o or s, you get slightly different error messages.
I was unlucky enough to have this happen several call layers inside a 2-nested try-except, so the error showed up a mile away from the line that caused it.
print ("float_value : %f , digit_value : %d , string_value : %s" % (3.4, 5, 'somestring'))
float_value : 3.400000 , digit_value : 5 , string_value : somestring
Related
I am trying to do network automation task using python but ran with type error while running the below given script.
I AM STUCK AT SAME KIND OF ERROR, CAN YOU GUYS PLEASE HELP ME OUT HOW TO FIX THIS ?*
durai#durai-virtual-machine:~/Network Automation$ python3 session_details.py
devices list: ['1.1.1.1', '2.2.2.2', '6.6.6.6', '7.7.7.7', '', '']
establishing telnet session: 1.1.1.1 cisco cisco
--- connected to: 1.1.1.1
--- getting version information
Traceback (most recent call last):
File "/home/durai/Network Automation/session_details.py", line 82, in <module>
device_version = get_version_info(session)
File "/home/durai/Network Automation/session_details.py", line 65, in get_version_info
version_output_parts = version_output_lines[1].split(',')
**TypeError: a bytes-like object is required, not 'str'**
durai#durai-virtual-machine:~/Network Automation$
THE BELOW IS THE BLOCK OF CODE WHERE I AM GETTING ERROR !
#-----------------------------------------------------------------------
def get_version_info(session):
print ('--- getting version information')
session.sendline('show version | include Version')
result = session.expect(['>', pexpect.TIMEOUT])
# Extract the 'version' part of the output
version_output_lines = session.before.splitlines()
version_output_parts = version_output_lines[1].split(',')
version = version_output_parts[2].strip()
print ('--- got version: ', version)
return version
#-----------------------------------------------------------------------
FULL CODE FOR YOUR REFERENCE:
#!/usr/bin/python
import re
import pexpect
#-----------------------------------------------------------------------
def get_devices_list():
devices_list = []
file = open('devices', 'r')
for line in file:
devices_list.append( line.rstrip() )
file.close()
print ('devices list:', devices_list)
return devices_list
#-----------------------------------------------------------------------
def connect(ip_address, username, password):
print ('establishing telnet session:', ip_address, username, password)
telnet_command = 'telnet ' + ip_address
# Connect via telnet to device
session = pexpect.spawn('telnet ' + ip_address, timeout=20)
result = session.expect(['Username:', pexpect.TIMEOUT])
# Check for error, if so then print error and exit
if result != 0:
print ('!!! TELNET failed creating session for: ', ip_address)
exit()
# Enter the username, expect password prompt afterwards
session.sendline(username)
result = session.expect(['Password:', pexpect.TIMEOUT])
# Check for error, if so then print error and exit
if result != 0:
print ('!!! Username failed: ', username)
exit()
session.sendline(password)
result = session.expect(['>', pexpect.TIMEOUT])
# Check for error, if so then print error and exit
if result != 0:
print ('!!! Password failed: ', password)
exit()
print ('--- connected to: ', ip_address)
return session
#-----------------------------------------------------------------------
def get_version_info(session):
print ('--- getting version information')
session.sendline('show version | include Version')
result = session.expect(['>', pexpect.TIMEOUT])
# Extract the 'version' part of the output
version_output_lines = session.before.splitlines()
version_output_parts = version_output_lines[1].split(',')
version = version_output_parts[2].strip()
print ('--- got version: ', version)
return version
#-----------------------------------------------------------------------
devices_list = get_devices_list() # Get list of devices
version_file_out = open('version-info-out', 'w')
# Loop through all the devices in the devices list
for ip_address in devices_list:
# Connect to the device via CLI and get version information
session = connect(ip_address, 'cisco', 'cisco')
device_version = get_version_info(session)
session.close() # Close the session
version_file_out.write('IP: '+ip_address+' Version: '+device_version+'\n')
# Done with all devices and writing the file, so close
version_file_out.close()
Python has two different kinds of strings. Normal strings are Unicode, where the individual characters are several bytes long, to handle Unicode characters. Many activities (like networking) need to use byte strings, which are written b"abc".
That's the problem here. The pexpect module is returning a byte string. So, in this line:
version_output_parts = version_output_lines[1].split(',')
version_output_parts is a byte string, but ',' is a Unicode string, and you can't mix them. So, you can either keep it bytes and do this:
version_output_parts = version_output_lines[1].split(b',')
or you can convert it to a Unicode string:
version_output_parts = version_output_parts.decode('utf-8')
version_output_parts = version_output_lines[1].split(b',')
It depends on how much you need to do with the parts.
It's the part where you extract the version that is bugged.
Try using print statements as demonstrated below to check the data types of your variables at each step.
This error suggests that you are using a method that is not available for the given data type e.g. calling a string method on an array or so on.
def get_version_info(session):
print ('--- getting version information')
session.sendline('show version | include Version')
result = session.expect(['>', pexpect.TIMEOUT])
# Extract the 'version' part of the output
version_output_lines = session.before.splitlines()
# print(version_output_lines)
version_output_parts = version_output_lines[1].split(',')
# print(version_output_parts)
version = version_output_parts[2].strip()
# print(version)
print ('--- got version: ', version)
return version
EDIT to format:
This is the original code
from __future__ import print_function
import socket
import sys
def socket_accept():
conn, address = s.accept()
print("Connection has been established | " + "IP " + address[0] + "| Port " + str(address[1]))
send_commands(conn)
conn.close()
def send_commands(conn):
while True:
cmd = raw_input()
if cmd == 'quit':
conn.close()
s.close()
sys.exit()
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024), "utf-8")
print(client_response, end ="")
def main():
socket_accept()
main()
I am getting this error “TypeError: str() takes at most 1 argument (2 given)” at “client_response” variable
You have your error here:
client_response = str(conn.recv(1024), "utf-8")
Just change it to:
client_response = str(conn.recv(1024)).encode("utf-8")
On the second to last line you're passing two arguments to the str function, although the str function only takes a single argument in Python 2. It does in fact take up to three arguments in python 3
https://docs.python.org/2.7/library/functions.html?highlight=str#str
https://docs.python.org/3.6/library/functions.html?highlight=str#str
So you're either trying to inadvertaetly run python 3 code in a python 2 interpreter or you're looking at the wrong language documentation.
So either use #franciscosolimas's answer, if you're using python 2, or make sure you're using python 3, if the latter you might also want to add a keyword argument just to make sure you know what's happening in the future
client_response = str(conn.recv(1024), encoding="utf-8")
3 arguments, 5 given
I got a similar error, may not be the same here (as the op) but, it was simple enough fix and wanted to share, since I ended up here from my searches on the error.
Traceback (most recent call last):
File "queries.py", line 50, in <module>
"WHERE ao.type='u';")
TypeError: str() takes at most 3 arguments (5 given)`
What fixed it for me in python3 was converting my ,'s to +
Error:
str("SELECT s.name + '.' + ao.name, s.name"
"FROM sys.all_objects ao",
"INNER JOIN sys.schemas s",
"ON s.schema_id = ao.schema_id",
"WHERE ao.type='u';"))
Fixed:
str("SELECT s.name + '.' + ao.name, s.name " +
"FROM sys.all_objects ao " +
"INNER JOIN sys.schemas s " +
"ON s.schema_id = ao.schema_id " +
"WHERE ao.type='u';")
I had to add my own spaces so the passed query would work.
As the commas were doing that in python...
Thoughts & my educated guess:
looks like in my case it got caught up trying to evaluate in bash/python a litteral u'
To my knowledge this break could be in bash because there is no command called u and/or in python u' is you trying to unicode an incomplete string. Either way it broke and wanted to share my fix.
Cheers!
~JayRizzo
I've got a weird problem. I've made a vba code in excel, that calls a python code that get information from the excel sheet and put it into a database. Yesterday there was no problem. Today I start my computer and tried the vba code and it errors in the python file.
The error:
testchipnr = TC104
Traceback (most recent call last):
testchipID = 108
File "S:/3 - Technical/13 - Reports & Templates/13 - Description/DescriptionToDatabase/DescriptionToDatabase.py", line 40, in <module>
TestchipID = cursorOpenShark.fetchone()[0] # Fetch a single row using fetchone() method and store the result in a variable., the [0] fetches only 1 value
TypeError: 'NoneType' object has no attribute '__getitem__'
The weird thing is that there is a value in the database -> testchipID ...
My code:
#get the testchipID and the testchipname
testchipNr = sheet.cell(7, 0).value # Get the testchipnr
print "testchipnr = ", testchipNr
queryTestchipID = """SELECT testchipid FROM testchip WHERE nr = '%s'""" %(testchipNr)
cursorOpenShark.execute(queryTestchipID)
print "testchipID = ", cursorOpenShark.fetchone()[0]
TestchipID = cursorOpenShark.fetchone()[0] # Fetch a single row using fetchone() method and store the result in a variable., the [0] fetches only 1 value
As you are saying, it was working fine but now it is not, the only reason that I can think of is when your query is returning Zero results.
Looking at your code, if your query is returning only one result, then it will print the result and the next time you are making the call to cursorOpenShark.fetchone() to store in TestchipID it would return None.
Instead, can you try the following code
#get the testchipID and the testchipname
testchipNr = sheet.cell(7, 0).value # Get the testchipnr
print "testchipnr = ", testchipNr
queryTestchipID = """SELECT testchipid FROM testchip WHERE nr = '%s'""" %(testchipNr)
cursorOpenShark.execute(queryTestchipID)
TestchipID = cursorOpenShark.fetchone()[0] # Fetch a single row using fetchone() method and store the result in a variable., the [0] fetches only 1 value
if TestchipID:
print "testchipID = ", TestchipID[0]
else:
print "Returned nothing"
Let me know if this works.
I have the following code that uses 3 strings 'us dollars','euro', '02-11-2014',
and a number to calculate the exchange rate for that given date. I modified the
code to pass those arguments but I get an error when I try to call it with
python currencyManager.py "us dollars" "euro" 100 "02-11-2014"
Traceback (most recent call last):
File "currencyManager.py", line 37. in <module>
currencyManager(currTo,currFrom,currAmount,currDate)
NameError: name 'currTo' is not defined
I'm fairly new to Python so my knowledge is limited. Any help would be greatly appreciated. Thanks.
Also the version of Python I'm using is 3.4.2.
import urllib.request
import re
def currencyManager(currTo,currFrom,currAmount,currDate):
try:
currency_to = currTo #'us dollars'
currency_from = currFrom #'euro'
currency_from_amount = currAmount
on_date = currDate # Day-Month-Year
currency_from = currency_from.replace(' ', '+')
currency_to = currency_to.replace(' ', '+')
url = 'http://www.wolframalpha.com/input/?i=' + str(currency_from_amount) + '+' + str(currency_from) + '+to+' + str(currency_to) + '+on+' + str(on_date)
req = urllib.request.Request(url)
output = ''
urllib.request.urlopen(req)
page_fetch = urllib.request.urlopen(req)
output = page_fetch.read().decode('utf-8')
search = '<area shape="rect.*href="\/input\/\?i=(.*?)\+.*?&lk=1'
result = re.findall(r'' + search, output, re.S)
if len(result) > 0:
amount = float(result[0])
print(str(amount))
else:
print('No match found')
except URLError as e:
print(e)
currencyManager(currTo,currFrom,currAmount,currDate)
The command line
python currencyManager.py "us dollars" "euro" 100 "02-11-2014"
does not automatically assign "us dollars" "euro" 100 "02-11-2014" to currTo,currFrom,currAmount,currDate.
Instead the command line arguments are stored in a list, sys.argv.
You need to parse sys.argv and/or pass its values on to the call to currencyManager:
For example, change
currencyManager(currTo,currFrom,currAmount,currDate)
to
import sys
currencyManager(*sys.argv[1:5])
The first element in sys.argv is the script name. Thus sys.argv[1:5] consists of the next 4 arguments after the script name (assuming 4 arguments were entered on the command line.) You may want to check that the right number of arguments are passed on the command line and that they are of the right type. The argparse module can help you here.
The * in *sys.argv[1:5] unpacks the list sys.argv[1:5] and passes the items in the list as arguments to the function currencyManager.
I'm create new project
I create two function. First func normally run, but second function not working
First func:
#it's work
def twitter(adress):
reqURL = request.urlopen("https://cdn.api.twitter.com/1/urls/count.json?url=%s" % adress)
encodingData = reqURL.headers.get_content_charset()
jsonLoad = json.loads(reqURL.read().decode(encodingData))
print("Sharing:", jsonLoad['count'])
Second func:
#Doesn't work
def facebook(adress):
reqURL = request.urlopen("https://api.facebook.com/method/links.getStats?urls=%s&format=json" % adress)
encodingData = reqURL.headers.get_content_charset()
jsonLoad = json.loads(reqURL.read().decode(encodingData))
print("Sharing:", jsonLoad['share_count'])
How to fix second func(facebook)
I get the error for facebook func:
Traceback (most recent call last):
File "/myproject/main.py", line 24, in <module>
facebook(url)
File "/myproject/main.py", line 15, in facebook
jsonLoad = json.loads(reqURL.read().decode(encodingData))
TypeError: decode() argument 1 must be str, not None
twitter func out:
Sharing: 951
How can I solve this problem?
Thanks
The Facebook response doesn't include a charset parameter indicating the encoding used:
>>> from urllib import request
>>> adress = 'www.zopatista.com'
>>> reqURL = request.urlopen("https://cdn.api.twitter.com/1/urls/count.json?url=%s" % adress)
>>> reqURL.info().get('content-type')
'application/json;charset=utf-8'
>>> reqURL = request.urlopen("https://api.facebook.com/method/links.getStats?urls=%s&format=json" % adress)
>>> reqURL.info().get('content-type')
'application/json'
Note the charset=utf-8 part in the Twitter response.
The JSON standard states that the default characterset is UTF-8, so pass that to the get_content_charset() method:
encodingData = reqURL.headers.get_content_charset('utf8')
jsonLoad = json.loads(reqURL.read().decode(encodingData))
Now, when no content charset parameter is set, the default 'utf8' is returned instead.
Note that Facebook's JSON response contains a list of matches; because you are passing in just one URL, you could take just the first result:
print("Sharing:", jsonLoad[0]['share_count'])