I saw this piece of code in a book and when I try to implement it I get a invalid syntax error.
This code basically reads a dictionary and writes into a txt file..
main.py
from Basics import data
dbfilename = 'people-file'
ENDDB = 'enddb.'
ENDREC = 'endrec.'
RECSEP = '=>'
def storelist(db,dbfilename):
print('In storelist function')
dbfile = open(dbfilename, 'w')
for key in db:
print(key, file=dbfile)
dbfile.close()
if __name__ == '__main__':
print('In Main list-items=',data.people)
storelist(data.people,dbfilename)
#for key in data.people:
# print('Values are', key['name'])
data.py
bob={'name':'bobs mith','age':42,'salary':5000,'job':'software'}
sue={'name':'sue more','age':30,'salary':3000,'job':'hardware'}
people={}
people['bob'] = bob
people['sue'] = sue
Error:
Syntax error:Invalid syntax.
Is it possible to write a file using a print statement.
I'm guessing you're really using python from the 2.x family. Print is a builtin function in python 3 and a statement in python 2. What happens if you try to print to a file using the 2.x syntax?
print >>dbFile, key
To check your version, open an interactive python shell and do
sys.version_info
I have 2.7, so I get
sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
You could just change it from using print to dbfile.write(key + "\n"). It is easier to understand what you are trying to accomplish.
If you're on python 2.6 or newer, you can try adding
from __future__ import print_function
Please ignore it..Its just a print statement..Its not a write statetement..I will delete this thread so that folks are not confused.
Related
I am trying to use the Kaggle api. I have downloaded kaggle using pip and moved kaggle.json to ~/.kaggle, but I haven't been able to run kaggle on Command Prompt. It was not recognized. I suspect it is because I have not accomplished the step "ensure python binaries are on your path", but honestly I am not sure what it means. Here is the error message when I try to download a dataset:
>>> sys.version
'3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)]'
>>> import kaggle
>>> kaggle datasets list -s demographics
File "<stdin>", line 1
kaggle datasets list -s demographics
^
SyntaxError: invalid syntax
kaggle is python module but it should also install script with the same name kaggle which you can run in console/terminal/powershell/cmd.exe as
kaggle datasets list -s demographics
but this is NOT code which you can run in Python Shell or in Python script.
If you find this script kaggle and open it in editor then you can see it imports main from kaggle.cli and it runs main()
And this can be used in own script as
import sys
from kaggle.cli import main
sys.argv += ['datasets', 'list', '-s', 'demographics']
main()
But this method sends results directly on screen/console and it would need assign own class to sys.stdout to catch this text in variable.
Something like this:
import sys
import kaggle.cli
class Catcher():
def __init__(self):
self.text = ''
def write(self, text):
self.text += text
def close(self):
pass
catcher = Catcher()
old_stdout = sys.stdout # keep old stdout
sys.stdout = catcher # assing new class
sys.argv += ['datasets', 'list', '-s', 'demographics']
result = kaggle.cli.main()
sys.stdout = old_stdout # assign back old stdout (because it is needed to run correctly `print()`
print(catcher.text)
Digging in source code on script kaggle I see you can do the same using
import kaggle.api
kaggle.api.dataset_list_cli(search='demographics')
but this also send all directly on screen/console.
EDIT:
You can get result as list of special objects which you can later use with for-loop
import kaggle.api
result = kaggle.api.dataset_list(search='demographics')
for item in result:
print('title:', item.title)
print('size:', item.size)
print('last updated:', item.lastUpdated)
print('download count:', item.downloadCount)
print('vote count:', item.voteCount)
print('usability rating:', item.usabilityRating)
print('---')
I wrote a program in Python-3.6.2 on Windows 10. I want get the CPU serial number.
Here is my code:
def getserial():
# Extract serial from cpuinfo file
cpuserial = "0000000000000000"
try:
f = open('/proc/cpuinfo','r')
for line in f:
if line[0:6]=='Serial':
cpuserial = line[10:26]
f.close()
except:
cpuserial = "ERROR000000000"
return cpuserial
print(getserial())
When I run the program, it prints: ERROR000000000.
How do I fix it?
Your code doesn't let any exception raised. So, you don't see the error: There is no '/proc/cpuinfo' file on Windows.
I have rewrite your code like that:
def getserial():
# Extract serial from cpuinfo file
with open('/proc/cpuinfo','r') as f:
for line in f:
if line[0:6] == 'Serial':
return line[10:26]
return "0000000000000000"
First, I have a with statement to use the file context manager: whenever an exception is raised or not, your file will be closed.
And I simplify the loop: if it found a "Serial" entry, it returns the value.
EDIT
If you have python with a version >= 2.6 you can simply use
import multiprocessing
multiprocessing.cpu_count()
http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count
EDIT2
The best solution I found to get the "cpuinfo" is with the py-cpuinfo library.
import cpuinfo
info = cpuinfo.get_cpu_info()
print(info)
But, I think that "Serial" entry is not standard. I can't see it on classic systems.
I've trying to decode qr or aztec code data by Python-zxing. Everytime I get empty data without any error in python Shell. What I do wrong?
import zxing
image = "aztec.png"
rd = zxing.BarCodeReader()
rs = rd.decode(image)
print rs.data
print rs
Output:
''
<zxing.BarCode instance at 0x0312A260>
Python ver. 2.7.11 (Windows)
P.S.
When I run script from cmd I've message:
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/zxing/client/j2se/CommandLineRunner
Assuming the mvn installation of Zxing is correct,add the path of the Zxing folder while creating an instance of reader (in this case 'rd')
rd = zxing.BarCodeReader("/path/to/zxing")
FYI: Am running it on Raspbian, not windows, but had the same error.
You forgot class inheritance. See below. Answer made compatible for python 3; but seriously... this is not the pep-way to do it. For long-term compatibility you should check by versioning and use an if-statement.
image = "aztec.png"
zxing = zxing() # notice zxhing()
rd = zxing.BarCodeReader()
rs = rd.decode(image)
try:
print (rs.data)
print (rs)
except:
print (rs.data)
print (rs)
print(rs.raw) # This returns the decoded text.
You can also use rs.parsed.
print(rs.format) # This returns the Format like the detected one is DataMatrix. QR Code etc.
print(rs.points) # This returns the boundary of points where its detected.
I have a python project I'm working on whereby instead of print statements I call a function say() so I can print information while in development and log information during production. However, I often forget this and put print statements in the code by mistake. Is there anyway to have the python program read its own source, and exit() if it finds any print statements outside of the function say()?
This can be done using the ast module. The following code will find any calls of the print statement and also of the print() function in case you are on Python 3 or Python 2 with the print_function future.
import ast
class PrintFinder(ast.NodeVisitor):
def __init__(self):
self.prints_found = []
def visit_Print(self, node):
self.prints_found.append(node)
super(PrintFinder, self).generic_visit(node)
def visit_Call(self, node):
if getattr(node.func, 'id', None) == 'print':
self.prints_found.append(node)
super(PrintFinder, self).generic_visit(node)
def find_print_statements(filename):
with open(filename, 'r') as f:
tree = ast.parse(f.read())
parser = PrintFinder()
parser.visit(tree)
return parser.prints_found
print 'hi'
for node in find_print_statements(__file__):
print 'print statement on line %d' % node.lineno
The output of this example is:
hi
print statement on line 24
print statement on line 26
While I don't recommend doing this, if you really want to you could have the Python interpreter throw an error by redefining the print statement.
If using Python 3, simply put this near the beginning / top of your code:
print = None
If there are any print statements, you will get a TypeError: 'NoneType' object is not callable error.
If using Python 2.x, you might use the idea suggested in another answer to allow Python 2.x to have an overridable print statement.
from __future__ import print_function
print = None
Putting this together with your say() function, you could do something like:
print_original = print
print = None
def say(data):
print = print_original
# Your current `say()` code here, such as:
print(data) # Could just use `print_original` instead.
# Redefine print to make the statement inaccessible outside this function.
print = None
Im using python 2.4.4 and for some reason it keeps throwing a type error when i try to open a log file for writing... Here is the function in question...
import os
def write(inlog, outlog):
# parse the logs and save them to our own...
parsed = NTttcpParse(inlog)
debug("PARSED")
debug(parsed)
if os.path.exists(outlog):
fh = os.open(outlog, os.O_WRONLY | os.O_APPEND)
debug("Opened '%s' for writing (%d)" % (outlog, fh))
else:
fh = os.open(outlog, os.O_WRONLY | os.O_CREAT)
debug("Created '%s' for writing (%d)" % (outlog, fh))
debug("type(fh) = %s" % type(fh))
os.write(fh, LOGFORMAT % parsed)
os.close(fh)
And here is the maddening error...
TypeError: int argument required
Please hel... and thanks in advance :P
You are doing file I/O in a strange way. Here is the way to do it:
f = open(outlog, "w")
f.write("some data written to file\n")
f.close()
If you want to append, use open(outlog, "a") instead. If you want to read, use open(outlog, "r"). Also read the Python tutorial, which explains basic file I/O operations like this.
Note that in Python 2.5 and up, you can use the with statement:
with open(outlog, "w") as f:
f.write("some data written to file\n")
(I originally posted this as the main answer before I noticed you said you were using 2.4.)
Yikes, i made a simple error-- i wasnt entering enough items in the parsed tuple ^_^ Thanks for your answers though!