when I try to run the code. I am getting an error.
The error is
Traceback (most recent call last):
File "A2.py", line 2, in <module>
from easysnmp import Session
ImportError: No module named 'easysnmp'
Note: I am getting the above error.Even though, I have installed easysnmp module.
The code is
#!/usr/bin/python
from easysnmp import Session
import argparse
import time
parser = argparse.ArgumentParser(description='probe')
parser.add_argument('cred',help='credentials')
parser.add_argument('freq',type=float,help='enter frequency')
parser.add_argument('samples',type=int,help='enter samples')
parser.add_argument('oid',nargs='+',help='enter oid')
args=parser.parse_args()
t=1/args.freq
s=args.samples
cred1=args.cred
ip,port,comm=cred1.split(":")
count=0
session=Session(hostname=ip,remote_port=port,community=comm, version=2,timeout=2,retries=1)
args.oid.insert(0, '1.3.6.1.2.1.1.3.0')
old=[]
out1=[]
t4=0
while (count!=s):
t1=time.time()
new = session.get(args.oid)
t2=time.time()
if len(new)==len(old):
newtime=float(new[0].value)/100
oldtime=float(old[0].value)/100
if args.freq > 1:
tdiff = newtime-oldtime
if args.freq <= 1:
tdiff1 = t1-t4
if tdiff!=0:
tdiff = int(tdiff1)
else:
tdiff = int(t)
for i in range(1,len(args.oid)):
if new[i].value!="NOSUCHINSTANCE" and old[i].value!="NOSUCHINSTANCE":
a=int(new[i].value)
b=int(old[i].value)
if a>=b:
out=(a-b)/tdiff
out1.append(out)
if a<b and new[i].snmp_type=="COUNTER64":
out=((2**64+a)-b)/tdiff
out1.append(out)
if a<b and new[i].snmp_type=="COUNTER32":
out=((2**32+a)-b)/tdiff
out1.append(out)
else:
print t1, "|"
count=count+1
if len(out1)!=0:
sar = [str(get) for get in out1]
print int(t1) ,'|', ("|" . join(sar))
old = new[:]
t4=t1
del out1[:]
t3=time.time()
if t-t3+t1>0:
time.sleep(t-t3+t1)
else:
time.sleep(0.0)
Try to put import easysnmp at the top of your code, it solved the problem for me at a similar situation!
My wild guess is that you installed the module for python 3 and used python 2 or the other way around.
Try
pip install easysnmp
or
pip3 install easysnmp
Related
I have imported a file image_function.py to my notebook. However when i tried using one of the functions im_reverse, it gave me an error.
Code:
import image_function
image_function.im_reverse("https://allhdwallpapers.com/wp-content/uploads/2015/05/sunset-8.jpg", reverse = 'horizontal', url = True)
Error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-61-afc744ac8a12> in <module>()
1 import image_function
----> 2 image_function.im_reverse("https://allhdwallpapers.com/wp-content/uploads/2015/05/sunset-8.jpg", reverse = 'horizontal', url = True)
/content/image_function.py in im_reverse(image_path, reverse, url)
45 mat_image_column_reverse[c][i] = mat_image_reverse[j][i]
46 c += 1
---> 47
48 plt.axis('off')
49
NameError: name 'requests' is not defined
The error happened before it reached the code for reversing vertically, which is down below.
What's inside image_function:
#libraries:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import imshow
from PIL import Image
import copy
import requests
from io import BytesIO
This is the code after the error:
def im_reverse(image_path, reverse = 'horizontal', url = True):
if url == True:
response = requests.get(image_path)
with Image.open(BytesIO(response.content)) as image:
mat_image = np.array(image, dtype=int)
m, n, depth = mat_image.shape
if reverse == 'horizontal':
mat_image_reverse = copy.deepcopy(mat_image)
mat_image_rows_reverse = copy.deepcopy(mat_image)
for i in range(m):
c = 0
for j in range(n-1,-1,-1):
mat_image_rows_reverse[i][c] = mat_image_reverse[i][j]
c += 1
plt.axis('off')
return imshow(mat_image_rows_reverse)
I have tried a lot of solutions on the web. However i dont see anything wrong. I have also tried a deliberate from requests import get or !pip install requests and it still didn't work.
Can anyone please offer a solution. Thanks
It sounds like you need to install requests:
python3 -m pip install requests
I am using the Python pocket sphinx tutorial, according to
https://metakermit.com/2011/python-speech-recognition-helloworld/
(complete code here):
import sys,os
def decodeSpeech(hmmd,lmdir,dictp,wavfile):
"""
Decodes a speech file
"""
try:
import pocketsphinx as ps
import sphinxbase
except:
print """Pocket sphinx and sphixbase is not installed
in your system. Please install it with package manager.
"""
speechRec = ps.Decoder(hmm = hmmd, lm = lmdir, dict = dictp)
wavFile = file(wavfile,'rb')
wavFile.seek(44)
speechRec.decode_raw(wavFile)
result = speechRec.get_hyp()
return result[0]
if __name__ == "__main__":
hmdir = "/usr/share/pocketsphinx/model/hmm/en_US/"
lmd = "/usr/share/pocketsphinx/model/lm/en_US/hub4.5000.DMP"
dictd = "/usr/share/pocketsphinx/model/lm/en_US/cmu07a.dic"
wavfile = sys.argv[1]
recognised = decodeSpeech(hmdir,lmd,dictd,wavfile)
print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
print recognised
print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
and when I run it I get the following error message:
Traceback (most recent call last):
File "hello.py", line 30, in <module>
recognised = decodeSpeech(hmdir,lmd,dictd,wavfile)
File "hello.py", line 17, in decodeSpeech
speechRec = ps.Decoder(hmm = hmmd, lm = lmdir, dict = dictp)
TypeError: __init__() got an unexpected keyword argument 'hmm'
Could you help me?
Looking at the pocketsphinx code on GitHub, in decoder_test.py we have an example of how to pass options to Decoder.
So it looks like your tutorial is for an old version and you actually want:
config = ps.Decoder.default_config()
config.set_string('-hmm', hmmd)
config.set_string('-lm', lmdir)
config.set_string('-dict', dictp)
speechRec = ps.Decoder(config)
I have copied all the codes to the work directory on all my engine machines. And my code are:
my_test.py
my_startegy.py
main.py
So, main.py will be ran on Client Machine, the codes in main.py are:
from ipyparallel import Client
import my_test
import my_strategy as strategy
class Beck_Test_Parallel(object):
"""
"""
def __init__(self):
self.rc = None
self.dview = None
def start_client(self, path):
self.rc = Client(path)
self.dview = self.rc[:]
#self.dview.push(dict(
# Account=my_test.Account,
# dataImport=my_test.dataImport
# ))
def parallel_map(self, deal_function, accounts):
import my_test
return self.dview.map_sync(deal_function, accounts)
def create_accounts(time_list, account):
accounts = []
for index, time in enumerate(time_list):
acc = my_test.Account(
strategy.start,
strategy.end,
strategy.freq,
strategy.universe_code,
strategy.capital_base,
strategy.short_capital,
strategy.benchmark,
strategy.self_defined
)
account.share_data(acc)
acc.iniData2()
acc.iniData3()
acc.current_time = time
acc.days_counts = index+1
acc.dynamic_record['capital'] = acc.capital_base
del acc.connect
accounts.append(acc)
return accounts
def let_us_deal(account):
account = strategy.handle_data(account)
print ' >>>', account.current_time
return account
if __name__ == '__main__':
account = my_test.Account(
strategy.start,
strategy.end,
strategy.freq,
strategy.universe_code,
strategy.capital_base,
strategy.short_capital,
strategy.benchmark,
strategy.self_defined
)
account.iniData()
account.iniData2()
account.iniData3()
time_list = my_test.get_deal_time_list(account)
accounts = parallel.create_accounts(time_list, account)
back_test_parallel = parallel.Beck_Test_Parallel()
back_test_parallel.start_client(
'/home/fit/.ipython/profile_default/security/ipcontroller-client.json')
back_test_parallel.dview.execute('import my_test')
back_test_parallel.dview.execute('import my_strategy as strategy')
# get the result
result = back_test_parallel.parallel_map(let_us_deal, accounts)
for acc in result.get():
print acc.reselected_stocks, acc.current_time
And I have imported my_test module in parallel_map() function in Class Back_Test_Parallel and I have also imported my_test module in back_test_parallel.dview.execute('import my_test').
And the corresponding modules are on the engine machine's work directory. I have copied the ipcontroller-client.json and ipcontroller-engine.json to the work directory on engine machine.
But when it runs, the error is ImportError: No module named my_test, since the module my_test.py is already on the work directory. It really made me feel frustrated!
---------------------------------------------------------------------------
CompositeError Traceback (most recent call last)
/home/fit/log/1027/back_test/main.py in <module>()
119 import ipdb
120 ipdb.set_trace()
--> 121 for acc in result.get():
122 print acc.reselected_stocks, acc.current_time
123
/usr/local/lib/python2.7/dist-packages/ipyparallel/client/asyncresult.pyc in get(self, timeout)
102 return self._result
103 else:
--> 104 raise self._exception
105 else:
106 raise error.TimeoutError("Result not ready.")
CompositeError: one or more exceptions from call to method: let_us_deal
[0:apply]: ImportError: No module named my_test
[1:apply]: ImportError: No module named my_test
something about result:
In [2]: result
Out[2]: <AsyncMapResult: finished>
In [3]: type(result)
Out[3]: ipyparallel.client.asyncresult.AsyncMapResult
Note that, when it runs on single machine by using ipcluster start -n 8, it works fine, without any error.
Thanks in advance
I think my CWD is not in the right directory. So you can check your CWD
>>> import os
>>> print(dview.apply_sync(os.getcwd).get())
If it is in wrong directory, before parallel computing, you can set the right CWD to make sure you ipyparallel env is in the right work directory:
>>> import os
>>> dview.map(os.chdir, ['/path/to/my/project/on/engine']*number_of_engines)
>>> print(dview.apply_sync(os.getcwd).get())
You can also check your engines' name by
>>> import socket
>>> print(dview.apply_sync(socket.gethostname))
And it works fine!
pip install ipyparallel --upgrade
Hi I'm VERY new to programming, and I am working on my first program. I've been following along in a book and I decided to stop and test a function. The function is in a file called myPythonFunctions.py. I then created a new file called untitled.py and put it in the same folder as myPythonFunctions.py.
In untitled.py I have the following code:
import myPythonFunctions as m
m.generateQuestion()
Very simple, but when I try to run it I get Import Error: no module named myPythonFunctions.
I don't understand, there is clearly a file named myPythonFunctions in the folder. What's going on?
In case you need it, here is the code for m.generateQuestion()
def generateQuestion():
operandList = [0,0,0,0,0,]
operatorList = ['', '', '', '', '']
operatorDict = [1:'+', 2:'-', 3:'*', 4:'**']
for index in range(0,5):
operandList[index] = randint(1,9)
for index in range(0,4):
if index > 0 and operatorList[index-1] !='**':
operator = operatorDict[randint(1,4)]
else:
operator = operatorDict[randint(1,3)]
operatorList[index] = operator
questionString = str(operandList[0])
for index in range(1,5):
questionString = questionString + OperatorList[index-1] + str[operandList[index]
result = eval(questionString)
questionString.replace("**","^")
print('\n' + questionString)
userAnswer=input('Answer: ')
while true:
try:
if int(userAnswer) == result:
print('Correct!')
return 1
else:
print('Sorry, the correct answer is', result)
return 0
except Exception as e:
print("That wasn't a number")
userAnswer = input('Answer: ')
Edit: I'm now getting this error
Traceback (most recent call last):
File "/Users/Brad/Desktop/Python/Untitled.py", line 1, in <module>
import myPythonFunctions as m
File "/Users/Brad/Desktop/Python/myPythonFunctions.py", line 33
operatorDict = [1:'+', 2:'-', 3:'*', 4:'**']
^
SyntaxError: invalid syntax
The syntaxis error you are getting, is because you are trying to define a dictionary as a list, so the interpreter is raising the error because it does not know what to do with that.
To define a dictionary you need to use { } instead of [ ]
--- EDIT 2
Your dictionary implementation is wrong, do you really copied this code from somewhere?
The
operatorDict = {1:'+', 2:'-', 3:'*', 4:'**'}
Your code was mispelled
---- EDIT
Your code on myPythonFunctions is really bad.
Python needs correct identation to works, please double check this step
I suggest you to do a check in your structure:
I did this right now
/somefolder
--this.py
--functions.py
/
The contents
--this.py
import functions as f
print f.hello()
--functions.py
def hello():
return 'It worked'
Try this structure in your environment :D
And then run:
python this.py
I am trying to execute this script:
import time
from SECEdgar.crawler import SecCrawler
def get_filings():
t1 = time.time()
# create object
seccrawler = SecCrawler()
companyCode = 'AAPL' # company code for apple
cik = '0000320193' # cik code for apple
date = '20010101' # date from which filings should be downloaded
count = '10' # no of filings
seccrawler.filing_10Q(str(companyCode), str(cik), str(date), str(count))
seccrawler.filing_10K(str(companyCode), str(cik), str(date), str(count))
seccrawler.filing_8K(str(companyCode), str(cik), str(date), str(count))
seccrawler.filing_13F(str(companyCode), str(cik), str(date), str(count))
t2 = time.time()
print "Total Time taken: ",
print (t2-t1)
if __name__ == '__main__':
get_filings()
I am putting this code in a file filings.py , then attempt to run it from terminal (Mac user)
python filings.py
But I am getting the following error:
Traceback (most recent call last):
File "filings.py", line 2, in <module>
from SECEdgar.crawler import SecCrawler
File "build/bdist.macosx-10.10-intel/egg/SECEdgar/crawler.py", line 6, in <module>
File "build/bdist.macosx-10.10-intel/egg/SECEdgar/config.py", line 22, in <module>
File "/Library/Python/2.7/site-packages/configparser.py", line 995, in __getitem__
raise KeyError(key)
KeyError: 'Paths'
What am I doing wrong?
Looks like there's an error in the package you installed.
Try uninstalling and reinstalling.
pip uninstall SECEdgar
pip install SECEdgar
I found the solution, it was basically a quite silly thing:
date = '20010101' # date from which filings should be downloaded
should be
date = '20010101' # date UNTIL which filings should be downloaded
so if you put the starting date you would end up with download 0 files, but if you put the end date then you would download them all successfully, seems to be working OK now :)