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.
Related
I am exporting a script I have made in Python that sends commands to IP Addresses of projectors to shut them down. The functionality of the code works, and the projectors will shut down. The list of projectors is stored in a dictionary in a different file to the script to allow it to be edited and accessed by other scripts.
Once I export my script to an exe using Pyinstaller v3.3.1 for Python 3.5.1, the .exe file no longer updates from the .py file that contains the dictionary, and instead has a version already stored in memory that I cannot update.
How can I make the executable file still read from the dictionary and update every time it is run?
Thanks,
Josh
Code:
dictonaryfile.py (reduced for security, but format shown).
projectors = {
'1': '192.168.0.1'
}
Script that performs shutdown
from pypjlink import Projector
from file3 import projectors
for item in projectors:
try:
myProjector = Projector.from_address(projectors[item])
myProjector.authenticate('PASSWORD REMOVED FOR SECURITY')
state = myProjector.get_power()
try:
if state == 'on':
myProjector.set_power('off')
print('Successfully powered off: ', item)
except:
print('The projector in ', item, ', raised an error, shutdown
may not have occurred')
continue
except:
print(item, 'did not respond to state request, it is likely powered
off at the wall.')
continue
As you noticed, once an exe is made, you can't update it. A workaround for a problem like this is ask for the location of dictonaryfile.py in your code-
from pypjlink import Projector
projector_location = input('Enter projector file location')
with open(projector_location) as f:
for line in f:
# extract data from f
....
For applications like these, it's a good idea to take a configuration file(.ini) and python has Configparser to read from config files. You could create your config file as -
[Projectors]
1 = '192.168.0.1'
2 = '192.168.0.45' # ..and so on
And read projectors from this file with Configparser -
config = configparser.ConfigParser()
config.read(projector_location)
projectors = config['PROJECTORS']
for k, v in projectors.items():
# your code here
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.
This is the code where I'm dumping all the data from .csv file into mongodb. What is strange is that it runs perfectly well on my mac but when I upload this code to Windows Azure running ubuntu 12.04.3 LTS only the main code gets executed and function is not called. Here's the code I'm using
import csv,json,glob,traceback
from pymongo import MongoClient
import datetime
import sys
import string
def make_document(column_headers,columns,timestamps):
#assert len(column_headers)==len(columns)
lotr = filter(lambda x: x[0] is not None,zip(column_headers,columns))
final = []
#print lotr
if not timestamps=={}:
for k,v in lotr:
try:
tformat = timestamps[k]
time_val = datetime.datetime.strptime(v,tformat)
final.append((k,time_val))
except KeyError:
final.append((k,v))
return dict(final)
else:
return dict(lotr)
def keep_printable_only(s):
return filter(lambda x: x in string.printable,s)
def perform(conf):
client = MongoClient(conf["server"],conf["port"])
db = client[conf["db"]]
collection = db[conf["collection"]]
files = glob.glob(conf["data_form"])
column_headers = conf["columns"]
csv_opts = {}
for k,v in conf["csv_options"].items():
csv_opts[str(k)]=str(v)
for infile in files:
#print conf["csv_options"]
inCSV = csv.reader(open(infile,'rU'),**csv_opts)
counter = 0
for record in inCSV:
yield record
counter +=1
if counter==2:
print record
#sys.exit(0)
record= map(keep_printable_only,record)
try:
doc = make_document(column_headers,record,conf["timestamp_columns"])
collection.insert(doc)
except :
print "error loading one of the lines : "
print traceback.format_exc()
if __name__=='__main__':
print"reads all data files of same format as given in column mapping and dumps them to a mongo collection"
print "uses conf.json.test as config file"
conf = json.load(open('./conf.json.txt'))
for row in perform(conf):
record= map(keep_printable_only,row)
When I run this on Azure, mongo collection is not created and the code terminates after printing the two lines in main code. I have no idea as to why this is happening.
Debug output would be very useful, in the form of a stack trace, as commented by #Alfe.
Further than that, it looks like your code stops at the line where you try to access a local file to read the configuration. Make sure that you can access the filesystem that way in Azure; sometimes providers put very strict walls between your code and the actual machine.
You can make your code more portable by using:
import os
import os.path
conf_filehandle = open(os.path.join(os.getcwd(), 'conf.json'))
conf = json.load(conf_filehandle)
Of course, you should also make sure that you have uploaded the JSON file to Azure :)
Excuse the unhelpful variable names and unnecessarily bloated code, but I just quickly whipped this together and haven't had time to optimise or tidy up yet.
I wrote this program to dump all the images my friend and I had sent to each other using a webcam photo sharing service ( 321cheese.com ) by parsing a message log for the URLs. The problem is that my multithreading doesn't seem to work.
At the bottom of my code, you'll see my commented-out non-multithreaded download method, which consistently produces the correct results (which is 121 photos in this case). But when I try to send this action to a new thread, the program sometimes downloads 112 photos, sometimes 90, sometimes 115 photos, etc, but never gives out the correct result.
Why would this create a problem? Should I limit the number of simultaneous threads (and how)?
import urllib
import thread
def getName(input):
l = input.split(".com/")
m = l[1]
return m
def parseMessages():
theFile = open('messages.html', 'r')
theLines = theFile.readlines()
theFile.close()
theNewFile = open('new321.txt','w')
for z in theLines:
if "321cheese" in z:
theNewFile.write(z)
theNewFile.close()
def downloadImage(inputURL):
urllib.urlretrieve (inputURL, "./grabNew/" + d)
parseMessages()
f = open('new321.txt', 'r')
lines = f.readlines()
f.close()
g = open('output.txt', 'w')
for x in lines:
a = x.split("<a href=\"")
b = a[1].split("\"")
c = b[0]
if ".png" in c:
d = getName(c)
g.write(c+"\n")
thread.start_new_thread( downloadImage, (c,) )
##downloadImage(c)
g.close()
There are multiple issues in your code.
The main issue is d global name usage in multiple threads. To fix it, pass the name explicitly as an argument to downloadImage().
The easy way (code-wise) to limit the number of concurrent downloads is to use concurrent.futures (available on Python 2 as futures) or multiprocessing.Pool:
#!/usr/bin/env python
import urllib
from multiprocessing import Pool
from posixpath import basename
from urllib import unquote
from urlparse import urlsplit
download_dir = "grabNew"
def url2filename(url):
return basename(unquote(urlsplit(url).path).decode('utf-8'))
def download_image(url):
filename = None
try:
filename = os.path.join(download_dir, url2filename(url))
return urllib.urlretrieve(url, filename), None
except Exception as e:
return (filename, None), e
def main():
pool = Pool(processes=10)
for (filename, headers), error in pool.imap_unordered(download_image, get_urls()):
pass # do something with the downloaded file or handle an error
if __name__ == "__main__":
main()
Did you make sure your parsing is working correctly?
Also, you are launching too many threads.
And finally... threads in python are FAKE! Use the multiprocessing module if you want real parallelism, but since the images are probably all from the same server, if you open one hundred connections at the same time with the same server, probably its firewall will start dropping your connections.
I'm trying to print the data that comes across the serial from an Arduino but I am unable to do so. My attempted code is this:
import serial
import time
s = serial.Serial('/dev/tty.usbmodemfd141',9600)
while 1:
if s.inWaiting():
val = s.readline(s.inWaiting())
print val
Yet after about 30 lines or so are spit out I get the following error message:
Traceback (most recent call last):
File "py_test.py", line 7, in <module>
val = s.readline(s.inWaiting())
File "build/bdist.macosx-10.8-intel/egg/serial/serialposix.py", line 460, in read
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)
I imagine I am using inWaiting incorrectly, but I do not see how to use it any other way.
Have you tried wrapping the readline in a try/except SerialException block? You could then just pass on the SerialException. It could be an issue with the serial driver reporting data in the receive buffer when there is not any, in which case your code will just keep running. Not a great fix, but it may lead you to the correct solution.
try:
s.read(s.inWaiting())
except serial.serialutil.SerialException:
pass # or maybe print s.inWaiting() to identify out how many chars the driver thinks there is
I believe you want to use function read(), not readline(). You are retrieving the number of characters in the buffer, they don't necessarily end with a new-line
Your loop becomes:
while 1:
if s.inWaiting():
val = s.read(s.inWaiting())
print val
if you want to simply print the data coming out of the serially connected device.you can
simply do it by using readline().
first open the port by using open() then you need to use the readline().
note:/dev/ttyUSB0 is a port number for linux and com0 is windows
here is the code
import serial
BAUDRATE = 115200
device_name = "ttyUSB0"
tty = device_name
s = serial.Serial("/dev/" + tty, baudrate=BAUDRATE)
s.open()
print s
try:
while True:
line = s.readline() //after this you can give the sleep time also as time.sleep(1) before that import time module.
print line
finally:
s.close()