I m getting error in running nested function in my python interpreter
import MySQLdb
import serial
import time
import smtplib
ser=serial.Serial('/dev/ttyACM1',9600)
db=MySQLdb.connect("localhost","root","pass","db")
cursor=db.cursor()
while 1:
print("Waiting ;;...")
print("")
print("collecting")
print("")
time.sleep(3)
x=ser.readline()
time.sleep(3)
if x>700:
send()
print"send mail"
print("inserting into Database")
sql="INSERT INTO vidit2(temp) VALUES(%s);" %(x)
cursor.execute(sql)
db.commit()
time.sleep(3)
def send():
content="send"
mail=smtplib.SMTP("smtp.gmail.com",587)
mail.ehlo()
mail.starttls()
mail.login("emailid","pass")
mail.sendmail("sender","reciever",content)
mail.close()
Error:
python temp.py
Waiting ;;...
collecting
Traceback (most recent call last):
File "temp.py", line 24, in
send()
NameError: name 'send' is not defined
Please help.
Thanks in Advance
Unlike, say, JavaScript which will "hoist" function definitions during compilation so that they can be called before they are defined in your code (just learned about this the other day so forgive me if this is an oversimplification), in Python you need to define functions before you call them (interesting discussion here). This means you need to do:
def send():
...
before:
send()
Related
I'm testing the execution of a crawler inside of the airflow structure. If I ran the following script, everything works fine and the payloads is printed.
from airflow import DAG
from airflow.models import BaseOperator, TaskInstance
from hooks.crawler_hook import CrawlerHook
from datetime import datetime
import time
class CrawlerOperator(BaseOperator):
def __init__(self, conn_id=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.conn_id = conn_id
def execute(self):
hook = CrawlerHook(conn_id=self.conn_id)
print(hook.run())
if __name__ == "__main__":
CrawlerOperator(task_id='test_run').execute()
But when I try to run a TaskInstance inside a DAG, I've got the an error and cannot understand why:
if __name__ == "__main__":
with DAG(dag_id="DAG1", start_date=datetime.now(), catchup=False) as dag:
to = CrawlerOperator(task_id="test_run")
ti = TaskInstance(task=to)
ti.run()
The error:
Traceback (most recent call last):
File "/home/../.env/lib/python3.8/site-packages/airflow/utils/session.py", line 67, in wrapper
return func(*args, **kwargs)
File "/home/../.env/lib/python3.8/site-packages/airflow/models/taskinstance.py", line 1123, in get_dagrun
dr = session.query(DagRun).filter(DagRun.dag_id == self.dag_id, DagRun.run_id == self.run_id).one()
File "/home/../.env/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 3500, in one
raise orm_exc.NoResultFound("No row was found for one()")
sqlalchemy.orm.exc.NoResultFound: No row was found for one()
Any suggestions?
I assume you are using it in some kind of unit test. What you are missing (and as the error indicates) is a DagRun:
from airflow.models import DagRun
DagRun(dag_id=self.dag.dag_id, execution_date=timezone.utcnow(), run_id="test")
ti.dag_run = dag_run
This is needed because tasks are associated to a DagRun not to a DAG.
DAG can have many DagRuns.
You can see example in one of the unit tests in Airflow codebase.
How do I get this code to work in 3?
Please note that I am not asking about "foo".upper() at the string instance level.
import string
try:
print("string module, upper function:")
print(string.upper)
foo = string.upper("Foo")
print("foo:%s" % (foo))
except (Exception,) as e:
raise
output on 2:
string module, upper function:
<function upper at 0x10baad848>
foo:FOO
output on 3:
string module, upper function:
Traceback (most recent call last):
File "dummytst223.py", line 70, in <module>
test_string_upper()
File "dummytst223.py", line 63, in test_string_upper
print(string.upper)
AttributeError: module 'string' has no attribute 'upper'
help(string) wasn't very helpful either. Far as I can tell, the only function left is string.capwords.
Note: a bit hacky, but here's a my short-term workaround.
import string
try:
_ = string.upper
except (AttributeError,) as e:
def upper(s):
return s.upper()
string.upper = upper
All of the string module-level functions you describe were removed in Python 3. The Python 2 string module documentation contains this note:
You should consider these functions as deprecated, although they will not be removed until Python 3.
If you have string.upper(foo) in Python 2, you need to convert that to foo.upper() in Python 3.
I'm starting using python to validate some json information, i'm using a json schema with reference but i'm having trouble to reference those files. This is the code :
from os.path import join, dirname
from jsonschema import validate
import jsonref
def assert_valid_schema(data, schema_file):
""" Checks whether the given data matches the schema """
schema = _load_json_schema(schema_file)
return validate(data, schema)
def _load_json_schema(filename):
""" Loads the given schema file """
relative_path = join('schemas', filename).replace("\\", "/")
absolute_path = join(dirname(__file__), relative_path).replace("\\", "/")
base_path = dirname(absolute_path)
base_uri = 'file://{}/'.format(base_path)
with open(absolute_path) as schema_file:
return jsonref.loads(schema_file.read(), base_uri=base_uri, jsonschema=True, )
assert_valid_schema(data, 'grandpa.json')
The json data is :
data = {"id":1,"work":{"id":10,"name":"Miroirs","composer":{"id":100,"name":"Maurice Ravel","functions":["Composer"]}},"recording_artists":[{"id":101,"name":"Alexandre Tharaud","functions":["Piano"]},{"id":102,"name":"Jean-Martial Golaz","functions":["Engineer","Producer"]}]}
And i'm saving the schema and reference file, into a schemas folder :
recording.json :
{"$schema":"http://json-schema.org/draft-04/schema#","title":"Schema for a recording","type":"object","properties":{"id":{"type":"number"},"work":{"type":"object","properties":{"id":{"type":"number"},"name":{"type":"string"},"composer":{"$ref":"artist.json"}}},"recording_artists":{"type":"array","items":{"$ref":"artist.json"}}},"required":["id","work","recording_artists"]}
artist.json :
{"$schema":"http://json-schema.org/draft-04/schema#","title":"Schema for an artist","type":"object","properties":{"id":{"type":"number"},"name":{"type":"string"},"functions":{"type":"array","items":{"type":"string"}}},"required":["id","name","functions"]}
And this is my error :
Connected to pydev debugger (build 181.5281.24)
Traceback (most recent call last):
File "C:\Python\lib\site-packages\proxytypes.py", line 207, in __subject__
return self.cache
File "C:\Python\lib\site-packages\proxytypes.py", line 131, in __getattribute__
return _oga(self, attr)
AttributeError: 'JsonRef' object has no attribute 'cache'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python\lib\site-packages\jsonref.py", line 163, in callback
base_doc = self.loader(uri)
<MORE>
python version : 3.6.5
windows 7
Ide : intellijIdea
Can somebody help me?
Thank you
I am not sure why, but on Windows, the file:// needs an extra /. So the following change should do the trick
base_uri = 'file:///{}/'.format(base_path)
Arrived at this answer from a solution posted for a related issue in json schema
I have been trying to use nltk.pos_tag in my code but I face an error when I do so. I have already downloaded Penn treebank and max_ent_treebank_pos. But the error persists. here is my code :
import nltk
from nltk import tag
from nltk import*
a = "Alan Shearer is the first player to score over a hundred Premier League goals."
a_sentences = nltk.sent_tokenize(a)
a_words = [nltk.word_tokenize(sentence) for sentence in a_sentences]
a_pos = [nltk.pos_tag(sentence) for sentence in a_words]
print(a_pos)
and this is the error I get :
"Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
print (nltk.pos_tag(text))
File "C:\Python34\lib\site-packages\nltk\tag\__init__.py", line 110, in pos_tag
tagger = PerceptronTagger()
File "C:\Python34\lib\site-packages\nltk\tag\perceptron.py", line 140, in __init__
AP_MODEL_LOC = 'file:'+str(find('taggers/averaged_perceptron_tagger/'+PICKLE))
File "C:\Python34\lib\site-packages\nltk\data.py", line 641, in find
raise LookupError(resource_not_found)
LookupError:
Resource 'taggers/averaged_perceptron_tagger/averaged_perceptron
_tagger.pickle' not found. Please use the NLTK Downloader to
obtain the resource: >>> nltk.download()
Searched in:
- 'C:\\Users\\T01142/nltk_data'
- 'C:\\nltk_data'
- 'D:\\nltk_data'
- 'E:\\nltk_data'
- 'C:\\Python34\\nltk_data'
- 'C:\\Python34\\lib\\nltk_data'
- 'C:\\Users\\T01142\\AppData\\Roaming\\nltk_data'
Call this from python:
nltk.download('averaged_perceptron_tagger')
Had the same problem in a Flask server. nltk used a different path when in server config, so I recurred to adding nltk.data.path.append("/home/yourusername/whateverpath/") inside of the server code right before the pos_tag call
Note there is some replication of this question
How to config nltk data directory from code?
nltk doesn't add $NLTK_DATA to search path?
POS tagging with NLTK. Can't locate averaged_perceptron_tagger
To resolve this error run following command on python prompt:
import nltk
nltk.download('averaged_perceptron_tagger')
I have a question to Ctypes and do not know what I do wrong. And yes, I am a newbie for Python and searched the other posts in here. So any advice is appreciated.
What do I want to do :
I simply want to load the FXCM C++ APP fundtions into Python 3.3 so I can call them for connecting to their server.
As it seems Ctypes seems to be the best tool. So a simple code in Python :
import os
dirlist = os.listdir('ForexConnectAPIx64/bin')
from pprint import pprint
pprint(dirlist)
from ctypes import *
myDll = cdll.LoadLibrary ("ForexConnectAPIx64/bin/ForexConnect.dll")
gives a result :
Traceback (most recent call File "C:\Users\scaberia3\Python_Projects \FTC\ListDir_Test.py", line 20, in <module>
myDll = cdll.LoadLibrary ("ForexConnectAPIx64/bin/ForexConnect.dll")
File "C:\Python33\lib\ctypes\__init__.py", line 431, in LoadLibrary
return self._dlltype(name)
File "C:\Python33\lib\ctypes\__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] Das angegebene Modul wurde nicht gefunden (Module not found)
['ForexConnect.dll',
'fxmsg.dll',
'gsexpat.dll',
'gslibeay32.dll',
'gsssleay32.dll',
'gstool2.dll',
'gszlib.dll',
'java',
'log4cplus.dll',
'msvcp80.dll',
'msvcr80.dll',
'net',
'pdas.dll']
Means the path is correct ForextConnect.dll is present and I might do some very simple wrong, but have no clue what.
You can either use Dependency Walker to figure out the correct sequence to manually load the DLLs, or simply add the directory to the system search path:
dllpath = os.path.abspath('ForexConnectAPIx64/bin')
os.environ['PATH'] += os.pathsep + dllpath
myDLL = CDLL('ForexConnect.dll')