Issue with importing and printing variable - python

Recently, I've tried to get comfortable with the open and write functions. I've encountered a problem which goes as follows: I use one script to write email = example#gmail.com in a file named "config.py". This is done using the following code: (All sensitive info has been replaced)
email = raw_input("What is your email? ")
f = open("config.py","w") #opens file
f.write("email = '{}'".format(email))
f.close() #This needs to be here else the file won't save
Then I try to import and open config.py in a separate script which looks like this:
import config
print email
However, I receive this error message:
Traceback (most recent call last):
File "/Users/MyUser/Desktop/untitled folder/Savetests/savetest_loading.py", line 1, in <module>
import config
File "/Users/MyUser/Desktop/untitled folder/Savetests/config.py", line 1
email = example#gmail.com
^
SyntaxError: invalid syntax
I have tried writing the file with quotations however this creates conflicts with the .format(). I am using python 2.7
My question is what should I do?
Thank you,
User

You need to quote the email:
email = 'example#gmail.com'
And in the module where import it, qualify the email with module name:
import config
print config.email
Or import email using from .. import .. statement:
from config import email
print email

Related

ValueError: source code string cannot contain null bytes when importing a package in python

from pyModbusTCP.client import ModbusClient
I am using pycharm and I have a class file which uses methods from pyModbusTCP package to communicate with devices over modbus. This class files exists as part of a directory in my project, where under the project folder I have a folder for device1 containing that particular class file along with some others. The idea was to simply duplicate the folder and title it device2, the intent being device2 functions as a backup to device1.
I created a device2 folder, made a main.py and copied most of the other contents from device1. The console is giving me only the error from the title at line 1, meaning the very first import statement that I linked is the cause for me receiving the error from the title. Given all that I have no idea what the error is even referring to, could anyone help me troubleshoot? Thanks!
EDIT:
Traceback (most recent call last):
File "/home/env1/Simulation/main.py", line 11, in <module>
import read_from_modbus
File "/home/env1/Simulation/read_from_modbus.py", line 1, in <module>
from pyModbusTCP.client import ModbusClient
ValueError: source code string cannot contain null bytes

ModuleNotFoundError: No module named '_beatbox'

I am trying to use python to connect with SF.
Saw some articles that show how to use it with beatbox library and I did install it.
However when trying to run simple code I'm getting error below.
Traceback (most recent call last):
File "c:/Users/user/hello/.vscode/hello.py", line 16, in <module>
import beatbox
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\beatbox\__init__.py", line 1, in <module>
from _beatbox import _tPartnerNS, _tSObjectNS, _tSoapNS, SoapFaultError, SessionTimeoutError
ModuleNotFoundError: No module named '_beatbox'
I navigate to the folder where the beatbox is installed and I see there the file _beatbox.py.
I think the file __init__.py try to import _beatbox but cannot find it for some reason.
Any idea how to solve it? What I'm missing?
Code:
import beatbox
sf_username = "xxxxxx"
sf_password = "xxxxxx"
sf_token = "xxxxxx"
def getAccount():
sf = beatbox._tPartnerNS
sf_client = beatbox.PythonClient()
password = str("%s%s" % (sf_password, sf_token))
sf_client.login(sf_username, sf_password)
accQuery = "Select Id,Name From Account limit 5"
queryResult = sf_client.query(accQuery)
print ("query result: " + str(queryResult[sf.size]))
for rec in queryResult[sf.records:]:
print str(rec[2]) + " : " + str(rec[3])
return
Can close the case. I first found that in python 3+ should use beatbox3. But then found additional errors (possible compatibility issues).
Since I notice it taking me too long, instead I tried using library simple-salesforce 0.74.2 to connect, and it worked perfect.
Probably, Python does not know where to search for the module. By default, only the sitepackages directory and your working directory is searched. You can resove this by placing a symbolic link to the beatbox package or moving it to the sitepackages directory
If you change the sitepackage folder name from "beatbox" to "_beatbox" this will solve your problem. You can then import it as: "import beatbox" and it will load in Python.

Import .json to Database

I successfully downloaded tweets into a json file. Now I try to import it in a database with this function:
def import_json(fi):
logging.warning("Loading tweets from json file {0}".format(fi))
for line in open(fi, "rb"):
data = json.loads(line.decode('utf-8'))
database.create_tweet_from_dict(data)
the json-file "keywords_BVBS04.json" lays in a folder called data which is in the current directory. The function is in a file called BVBS04.py
to start the import I type BVBS04.import_json(keywords_BVBS04.json) in ipython in the console. this is what I get back:
NameError Traceback (most recent call
last) in ()
----> 1 BVBS04.import_json(keywords_BVBS04.json)
NameError: name 'keywords_BVBS04' is not defined
Now here comes the is a beginner's question: Where/how do I have to define "keywords_BVBS04"? I tried a lot :(
Thanks!
This is what you want,
1) you need to import the function from the script, not use dot-notation on the script.
2) Quote the filename.
>>> from BVBS04 import import_json
>>> import_json("keywords_BVBS04.json")
Good luck with the rest of things

Sending E-mail Hotmail Account via Raspberry Pi

I just write this code in Python under Raspbian OS:
import smtplib
from = '****#hotmail.de'
to = '****#hotmail.de'
msg = 'Testmail'
usr = '****#hotmail.de'
psw = '****'
server = smtplib.SMTP('smtp.live.de',25)
server.login (usr,psw)
server.sendmail (from, to, msg)
server.quit()
And get following Error-Message:
Traceback (most recent call last):
File "ail.py", line 1, in <module>
import smtplib
File "/usr/lib/python2.7/smtplib.py", line 46, in <module>
import email.utils
File "/home/pi/email.py", line 6, in <module>
smtp =smtplib.SMTP('smtp.live.com',25)
AttributeError: 'module' object has no attribute 'SMTP'
What is my fault? Could somebody help me - please?
Regards
Your problem is that you named your script email.py, or maybe an earlier version of it. That means that it shadows the standard-library email module/package. So, when smtplib tries to import email or import email.utils, it gets your code instead of the stdlib code it wants.
The solution is to rename your script to not match any of the stdlib modules and packages (or at least not any of the ones you're directly or indirectly using).
If you've already renamed it to ail.py (as the traceback seems to suggest) and it's still causing problems, make sure to delete your original email.py, and any .pyc/.pyo files of the same name. As long as they're in the current working directory (or elsewhere on sys.path), they can still interfere with the stdlib.

Fixed: Python NameError, fixed AttributeError and got this?

FIXED: turns out there is a module already called parser. Renamed it and its working fine! Thanks all.
I got a python NameError I can't figure out, got it after AttributeError. I've tried what I know, can't come up with anything.
main.py:
from random import *
from xml.dom import minidom
import parser
from parser import *
print("+---+ Roleplay Stat Reader +---+")
print("Load previous DAT file, or create new one (new/load file)")
IN=input()
splt = IN.split(' ')
if splt[0]=="new":
xmlwrite(splt[1])
else:
if len(splt[1])<2:
print("err")
else:
xmlread(splt[1])
ex=input("Press ENTER to Exit...")
parser.py:
from xml.dom import minidom
from random import *
def xmlread(doc):
xmldoc = minidom.parse(doc)
itemlist = xmldoc.getElementsByTagName('item')
for s in itemlist:
print(s.attributes['name'].value,":",s.attributes['value'].value)
def xmlwrite(doc):
print("no")
And no matter what I get the error:
Traceback (most recent call last):
File "K:\Python Programs\Stat Reader\main.py", line 10, in <module>
xmlwrite.xmlwrite(splt[1])
NameError: name 'xmlread' is not defined
The same error occurs when trying to access xmlwrite.
When I change xmlread and xmlwrite to parser.xmlread and parser.xmlwrite I get:
Traceback (most recent call last):
File "K:\Python Programs\Stat Reader\main.py", line 15, in <module>
parser.xmlread(splt[1])
AttributeError: 'module' object has no attribute 'xmlread'
The drive is K:\ because it's my personal drive at my school.
If your file is really called parser.xml, that's your problem. It needs to be parser.py in order to work.
EDIT: Okay, since that wasn't your issue, it looks like you have a namespacing issue. You import your parser module twice when you use import parser and then from parser import *. The first form of it makes "parser" the namespace and the second form directly imports it, so in theory, you should have both parser.xmlwrite and xmlwrite in scope. It's also clearly not useful to import minidom in main.py since you don't use any minidom functionality in there.
If you clear up those and still have the issue, I would suggest looking at __ init __.py. If that still does nothing, it could just plain be a conflict with Python's parser module, you could substitute a name like myxmlparser.

Categories

Resources