Im busy with a project for my study and I keep getting this error:
Exception in thread Thread-62:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
TypeError: 'long' object is not callable
The function that produces this error is:
teller = 0
def toRedis(dstip, srcip, dnsname):
global teller
ignoreDom = config.getSetting('setup', 'ignore')
if dnsname in ignoreDom:
pass
else:
teller += 1
answer = {"_id": teller, "destination": dstip, "source": srcip, "name": dnsname}
r_serv.hmset("_id" + str(teller), answer)
t = threading.Thread(target=r_serv.hset("_id" + str(teller),
"vt", VTHandler(r_serv.hget("_id" + str(teller), "source"))))
t.daemon = True
t.start()
print r_serv.hgetall("_id" + str(teller))
I'm pretty sure it comes from the thread, as that is inside the error. But I can't figure out what is going wrong, it seems just fine to me. At the first few moments it doesn't give me an error but after 20 seconds or so, the error keeps popping up, even tho the script keeps running while these errors are printed out.
t = threading.Thread(target=r_serv.hset("_id" + str(teller),
"vt", VTHandler(r_serv.hget("_id" + str(teller), "source"))))
You are calling the r_serv.hset function and then assigning its return value to the target kwarg (which is then being called and raising the exception), instead of assigning the function itself to the target kwarg.
What you should be doing is:
t = threading.Thread(target=r_serv.hset, args=("_id" + str(teller),
"vt", VTHandler(r_serv.hget("_id" + str(teller), "source"))))
Related
Hello i m trying to use Popen to open a .py and pass arg, if necessary, to it.
exemple:
python mytool.py --first-arg player1 player2 player3 --second-arg 10 --tenth-arg 150
I m using a tkinter button to start this funcion, it works on Windows using python 3.7
but not on linux, getting this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "mytool.py", line 131, in start
obj = subprocess.Popen([self.Tipvar.get(), 'mytool.py', *filter(lambda x: bool(x[1]) ,(first_arg, second_arg, third_arg, fourth_arg, fifth_arg, sixth_arg, seventh_arg, eighth_arg, ninth_arg, tenth_arg, eleventh_arg, twelfth_arg))])
File "/usr/lib/python3.7/subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.7/subprocess.py", line 1453, in _execute_child
restore_signals, start_new_session, preexec_fn)
TypeError: expected str, bytes or os.PathLike object, not tuple
The code i m using is this one:
def start(self):
first_arg = ("--first-arg ", self.first_arg_entry.get())
second_arg = ("--second-arg ", self.second_arg_entry.get())
third_arg = ("--third_arg-arg ", self.third_arg_entry.get())
fourth_arg = ("--fourth-arg ", self.fourth_arg_entry.get())
fifth_arg = ("--fifth-arg ", self.fifth_arg_entry.get())
sixth_arg = ("--sixth-arg ", self.sixth_arg_entry.get())
seventh_arg = ("--seventh-arg ", self.seventh_arg_entry.get())
eighth_arg = ("--eighth-arg ", self.eighth_arg_entry.get())
ninth_arg = ("--ninth-arg ", self.ninth_arg_entry.get())
tenth_arg = ("--tenth-arg ", self.tenth_arg_entry.get())
eleventh_arg = ("--eleventh-arg ", self.eleventh_arg_entry.get())
twelfth_arg = ("--twelfth-arg ", self.twelfth_arg_entry.get())
thirteenth_arg = (self.vold.get())
print ("Tool started in terminal")
self.bt_stop.config(state=NORMAL)
self.disable_buttons()
global obj
if self.vold.get() == "":
obj = subprocess.Popen([self.Tipvar.get(), 'mytool.py', *filter(lambda x: bool(x[1]) ,(first_arg, second_arg, third_arg, fourth_arg, fifth_arg, sixth_arg, seventh_arg, eighth_arg, ninth_arg, tenth_arg, eleventh_arg, twelfth_arg))])
else:
obj = subprocess.Popen([self.Tipvar.get(), 'myool.py', *filter(lambda x: bool(x[1]) ,(first_arg, second_arg, third_arg, fourth_arg, fifth_arg, sixth_arg, seventh_arg, eighth_arg, ninth_arg, tenth_arg, eleventh_arg, twelfth_arg, thirteenth_arg))])
What can I be doing wrong and what can be done to work on Linux/Windows?
Hope you help me.
You are sending tuple(args in round brankets) in the subprocess call, which I think is causing the issue.
Pls. check the subprocess documentation for more details, how to pass the args and also use the type() operator if you are not sure about the datatypes
Running this snippet of code:
while True:
print('recording')
myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=1, dtype=np.int16)
sd.wait() # Wait until recording is finished
write('output.wav', fs, myrecording.astype(np.int16))
sound = AudioSegment.from_file("output.wav", format="wav")
lsound = sound + 35
silence = silence.detect_nonsilent(lsound, min_silence_len=1000, silence_thresh=-15)
silence = [((start/1000),(stop/1000)) for start,stop in silence] #convert to sec
print(silence)
print(len(silence))
if len(silence) == 0:
print('silence')
else:
print('have recording')
lsound.export("loutput.wav", format='wav')
During first iteration every thing works fine
recording
[(0.0, 0.502), (1.842, 5.0)]
2
have recording
But during next iteration get:
recording
Traceback (most recent call last):
File "sttgft.py", line 43, in <module>
silence = silence.detect_nonsilent(lsound, min_silence_len=1000, silence_thresh=-15)
AttributeError: 'list' object has no attribute 'detect_nonsilent'
Attempted to delete 'silence' with del silence command but then get;
Traceback (most recent call last):
File "sttgf1.py", line 43, in <module>
silence = silence.detect_nonsilent(lsound, min_silence_len=1000, silence_thresh=-15)
NameError: name 'silence' is not defined
Don't know what to try
If you delete silence then the line of code below will throw an error as to get the final silence, it must be already there.
silence = silence.detect_nonsilent(lsound, min_silence_len=1000, silence_thresh=-15)
Now check what is the value of silence before while loop, because once it completes the first iteration silence becomes a list datatype and the same line of code mentioned above will do a list.detect_nonsilent. That is why you are getting the first error after first iteration.
Stupid mistake. Using the name 'silence' in 'silence = silence.detect_nonsilent...'
caused the error. once I changed to "silenc = silence.detect_nonsilent..." it worked perfectly.
edited..
full traceback:
Traceback (most recent call last):
File "dscli.py", line 36, in <module>
main()
File "dscli.py", line 31, in main
instance_StreamingDownloader.download_all()
File "file.py", line 283, in download_all
time_first_frame_last_segment = self.get_time_saved_segment(crrt_segment - 1)
File "file.py", line 239, in get_time_saved_segment
return(start_time)
UnboundLocalError: local variable 'start_time' referenced before assignment
code here
It gets only first segment and then error.
How can I solve this issue?
code from github
the answer is quite simple -
the condition allows some case when start_time is not defined during script run
so as it is not defined - it fails
start_time is defined inside an if statement that's inside a for loop.
What if you don't enter the loop, or the condition isn't met? What should the function return?
start_time needs to be initialized (eg start_time = 0 / None / False) in the function body, outside any control flow clauses, so that it's always defined, and therefore you can always return it.
when condition isn't met then:
Traceback (most recent call last):
File "dscli.py", line 36, in <module>
main()
File "dscli.py", line 31, in main
instance_StreamingDownloader.download_all()
File "file.py", line 286, in download_all
lenght_ahead_buffered = time_first_frame_last_segment - time_if_streaming + random_perturbation
TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'
line 280-286:
while continue_download:
time_first_frame_last_segment = self.get_time_saved_segment(crrt_segment - 1)
time_if_streaming = time.time() - init_time
random_perturbation = random.gauss(0, self.random_time)
if self.verbose > 1:
print("time in video if streaming: " + str(time_if_streaming))
I have a scrapy script that works locally, but when I deploy it to Scrapinghub, it's giving all errors. Upon debugging, the error is coming from Yielding the item.
This is the error I get.
ERROR [scrapy.utils.signal] Error caught on signal handler: <bound method ?.item_scraped of <sh_scrapy.extension.HubstorageExtension object at 0x7fd39e6141d0>> Less
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 150, in maybeDeferred
result = f(*args, **kw)
File "/usr/local/lib/python2.7/site-packages/pydispatch/robustapply.py", line 55, in robustApply
return receiver(*arguments, **named)
File "/usr/local/lib/python2.7/site-packages/sh_scrapy/extension.py", line 45, in item_scraped
item = self.exporter.export_item(item)
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 304, in export_item
result = dict(self._get_serialized_fields(item))
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 75, in _get_serialized_fields
value = self.serialize_field(field, field_name, item[field_name])
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 284, in serialize_field
return serializer(value)
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 290, in _serialize_value
return dict(self._serialize_dict(value))
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 300, in _serialize_dict
key = to_bytes(key) if self.binary else key
File "/usr/local/lib/python2.7/site-packages/scrapy/utils/python.py", line 117, in to_bytes
'object, got %s' % type(text).__name__)
TypeError: to_bytes must receive a unicode, str or bytes object, got int
It doesn't specify the field with issues, but by process of elimination, I came to realize it's this part of the code:
try:
item["media"] = {}
media_index = 0
media_content = response.xpath("//audio/source/#src").extract_first()
if media_content is not None:
item["media"][media_index] = {}
preview = item["media"][media_index]
preview["Media URL"] = media_content
preview["Media Type"] = "Audio"
media_index += 1
except IndexError:
print "Index error for media " + item["asset_url"]
I cleared some parts up to make it easier to tackle, but basically this part is the issue. Something it doesn't like about the item media.
I'm beginner in both Python and Scrapy. So sorry if this turns out to be silly basic Python mistake. Any idea?
EDIT: So after getting the answer from ThunderMind, the solution was to simply do str(media_index) for key
Yeah, right here:
item["media"][media_index] = {}
media_index is a mutable. and Keys can't be mutable.
Read Python dict, to know what should be used as keys.
Have a look at this code :
import threading
import time
def my_inline_function(number):
#do some stuff
download_thread = threading.Thread(target=function_that_writes, args=number)
download_thread.start()
#continue doing stuff
i = 0
while(i < 10000):
print str(i) + " : Main thread"
time.sleep(1)
i = i + 1
def function_that_writes(number):
i = number
file = open("dummy.txt", 'w')
while (i < 10000):
string = str(i) + " : child thread"
file.write(string)
time.sleep(1)
file.close()
my_inline_function(5)
function_that_writes(5)
With does my_inline_function(), which starts a thread, not create a file?
But when I am calling a function_that_writes(...) directly, which is not running in a thread, it is able to create a file.
Why am I getting this behaviour?
You need to supply your argument as a tuple args=(number,):
download_thread = threading.Thread(target=function_that_writes, args=(number,))
The exception is pretty clear here:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/Users/mike/anaconda/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/Users/mike/anaconda/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
TypeError: function_that_writes() argument after * must be an iterable, not int