Why expected string become an tuple [duplicate] - python

This question already has answers here:
member variable string gets treated as Tuple in Python
(3 answers)
Closed 6 years ago.
I expected the variable output_format to be a string. But when I ran the script it gave me a tuple type and threw an exception.
If I run in Python interpreter, it gave me an expected string.
('--sout "#standard{access=file,vcodec=h264,dst=c0_s0_h264_640x480_30_vbr_500_99_40000000.mp4}"',)
'h264'
<type 'str'>
Traceback (most recent call last):
File "streaming_verification/src/streaming_verification/scripts/streaming_verification.py", line 184, in run
self.streaming.dump_file(export_fname, 5, codec_type)
File "streaming_verification/src/streaming_verification/scripts/streaming.py", line 57, in dump_file
cmd_str = " ".join(cmd)
TypeError: sequence item 3: expected string, tuple found
Script source code:
def dump_file(self,
fname='',
period=10,
codec_type="h264"):
if "h264" == codec_type:
output_format = "--sout \"#standard{access=file,vcodec=h264,dst=%s.mp4}\"" % fname,
elif "mjpeg" == codec_type:
output_format = "--sout \"#standard{access=file,vcodec=mjpg ,dst=%s.avi}\"" % fname,
elif "mpeg" == codec_type :
output_format = "--sout \"#standard{access=file,vcodec=h264,dst=%s.mp4}\"" % fname,
pp(output_format)
cmd =[
"vlc",
"-I dummy",
"--rtsp-tcp {0}".format(self.conn_cfg["rtsp_link"]),
output_format,
"--stop-time {0} vlc://quit ".format(period)
]
cmd_str = " ".join(cmd)
self.run(cmd_str)

Your output_format is always tuple, because you put a comma after each possible value:
output_format = "..." % fname,
# ---------------------------^
Remove those commas and your cmd_str will once again only contain strings.
Python tuples are formed by such commas; the parenthesis are only needed when not using them would lead to ambiguity:
>>> 1
1
>>> 1,
(1,)
>>> type(_)
<class 'tuple'>

Related

Is there a way to item assignment for bytes object? [duplicate]

This question already has answers here:
Item assignment to bytes object?
(2 answers)
Closed 1 year ago.
I am trying to assign bytes to a portion of pcap data(using slice operation) as below. I am getting "TypeError: 'bytes' object does not support item assignment" when try to assign data [a[8:24] = new5]. If not supported, is there any way?
code:
x = rdpcap("ref.pcap")
for packet in x:
a = (bs.hexlify(bytes(packet.load)))
TTF = a[8:24]
print ("T1",TTF)
new0 = (TTF.decode('utf-8'))
print ("T1-decode",new0)
print ("T1-dec",int(new0, base=16))
new4 = hex(int(time.time()))[2:]
print ("new4",new4)
new5 = bytes(new4, encoding='utf8')
print ("new5",new5)
print (a[8:24])
a[8:24] = new5
output:
T1 b'60ac7bd500000000'
T1-decode 60ac7bd500000000
T1-decimal 6966078878393565184
new4 60af6be2
new5 b'60af6be2'
b'60ac7bd500000000'
Traceback (most recent call last):
File "<stdin>", line 15, in <module>
TypeError: 'bytes' object does not support item assignment
A bytestring is immutable. You need to make a copy.
data = b'this is a test'
new_data = data[:5] + b'was' + data[7:]
# or, using join():
# new_data = b''.join((data[:5], b'was', data[7:]))
new_data
output:
b'this was a test'
Alternatively, you could use a bytearray:
data = bytearray(b'this is a test')
data[5:7] = b'was'
data
output:
bytearray(b'this was a test')

Static method is causing an unexpected indent error? [duplicate]

This question already has answers here:
What should I do with "Unexpected indent" in Python?
(18 answers)
Closed 1 year ago.
For some reason when I run this code I get an unexpected indent error on the #staticmethod line, but I have no idea why! Everything is properly indented, but this is causing all of my methods to raise errors in code post. Also, I removed a few other methods from the class to shorten the code I'm posting on here.
class Reservation:
"""A data type that represents a hotel room booking system."""
booking_numbers = []
#staticmethod
def get_reservations_from_row(room_obj, list_tuples):
reservation_dict = {}
booking_num_list = []
date_list = []
for element in list_tuples:
year, month, day, short_str = element
list_short_str = short_str.split('--')
booking_num = int(list_short_str[0])
name = list_short_str[1]
if booking_num not in booking_num_list:
booking_num_list.append(booking_num)
date = datetime.date(year, month, day)
date_list.append(date)
for element in booking_num_list:
print(date_list)
date_list.sort()
value = Reservation(name, room_obj, date_list[0], date_list[len(date_list)-1], element)
reservation_dict[element] = reservation_dict.get(element, []) + value
return reservation_dict
Traceback (most recent call last):
File "/Applications/Thonny.app/Contents/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "/Users/myname/Downloads/reservation.py", line 74
#staticmethod
^
IndentationError: unexpected indent
It seems that you have used the tab for indentation.
Remove the tab and insert 4 spaces it will work for you

SyntaxError: Invalid syntax? Eval() [duplicate]

This question already has answers here:
Why must "exec" (and not "eval") be used for Python import statements?
(3 answers)
Closed 3 years ago.
Basically I am doing a POC against python eval security issue, but I am getting below error:
Traceback (most recent call last):
File "exploit.py", line 11, in <module>
a = paste()
File "exploit.py", line 6, in paste
if eval('%s > 1' % a):
File "<string>", line 1
import os;os.system('pwd') > 1
^
SyntaxError: invalid syntax
Code:
import datetime
def paste():
a = "import os;os.system('pwd')"
if eval('%s > 1' % a):
print a
else:
#create_brew(request.json)
return None, 201
a = paste()
print a
can anyone help me how to import libraries in-line?
eval works in expressions.
Use exec to execute a statement [import is a statement]
Also note, you cannot assign exec to a variable.
>> exec('import os;data = os.getcwd()')
>> print(data)
>> # /path/of/you/cwd
You may use the variable data to continue with your tests.
Taking the liberty to edit your code as follow:
def paste():
data = None
exec('import os;data = os.getcwd()')
if data:
return data
else:
return None, 201
a = paste()
print(a)

I am getting this error "TypeError: str() takes at most 1 argument (2 given)" at "client_response" variable

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

Python ValueError: chr() arg not in range(256)

So I am learning python and redoing some old projects. This project involves taking in a dictionary and a message to be translated from the command line, and translating the message. (For example: "btw, hello how r u" would be translated to "by the way, hello how are you".
We are using a scanner supplied by the professor to read in tokens and strings. If necessary I can post it here too. Heres my error:
Nathans-Air-4:py1 Nathan$ python translate.py test.xlt test.msg
Traceback (most recent call last):
File "translate.py", line 26, in <module>
main()
File "translate.py", line 13, in main
dictionary,count = makeDictionary(commandDict)
File "/Users/Nathan/cs150/extra/py1/support.py", line 12, in makeDictionary
string = s.readstring()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 105, in readstring
return self._getString()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 251, in _getString
if (delimiter == chr(0x2018)):
ValueError: chr() arg not in range(256)
Heres my main translate.py file:
from support import *
from scanner import *
import sys
def main():
arguments = len(sys.argv)
if arguments != 3:
print'Need two arguments!\n'
exit(1)
commandDict = sys.argv[1]
commandMessage = sys.argv[2]
dictionary,count = makeDictionary(commandDict)
message,messageCount = makeMessage(commandMessage)
print(dictionary)
print(message)
i = 0
while count < messageCount:
translation = translate(message[i],dictionary,messageCount)
print(translation)
count = count + 1
i = i +1
main()
And here is my support.py file I am using...
from scanner import *
def makeDictionary(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst = []
token = s.readtoken()
count = 0
while (token != ""):
lyst.append(token)
string = s.readstring()
count = count+1
lyst.append(string)
token = s.readtoken()
return lyst,count
def translate(word,dictionary,count):
i = 0
while i != count:
if word == dictionary[i]:
return dictionary[i+1]
i = i+1
else:
return word
i = i+1
return 0
def makeMessage(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst2 = []
string = s.readtoken()
count = 0
while (string != ""):
lyst2.append(string)
string = s.readtoken()
count = count + 1
return lyst2,count
Does anyone know whats going on here? I've looked through several times and i dont know why readString is throwing this error... Its probably something stupid i missed
chr(0x2018) will work if you use Python 3.
You have code that's written for Python 3 but you run it with Python 2. In Python 2 chr will give you a one character string in the ASCII range. This is an 8-bit string, so the maximum parameter value for chris 255. In Python 3 you'll get a unicode character and unicode code points can go up to much higher values.
The issue is that the character you're converting using chr isn't within the range accepted (range(256)). The value 0x2018 in decimal is 8216.
Check out unichr, and also see chr.

Categories

Resources