Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.

Share tech news, updates, or what's on your mind.

Sign up to Post

Hello Experts,

I have number of HP blade enclosures to pull data from.  I've written a Python script to SSH to the enclosures and retrieve the data.   The script works but takes about 3 hours to complete.   Although the bulk of the code in the script parses the data, the bulk of the time involved is in setting the SSH session to each server.   Thus what I'd like to do is establish a means to run the processes in parallel.    I'm hoping someone can give me pointers in the right direction.

What I've Tried


1. My first stab at this with with the Parallel-SSH module (https://pypi.python.org/pypi/parallel-ssh).   That would have been the cleanest solution.   However, although I was able to connect to my enclosures, I was unable to retrieve output from any of my commands.  
2.  My current work around is to use Python's Multiprocessing module and specifically a pool as that seemed to be the simplest solution.   However, that's not working.   From the output the use of pool.imap results in mangled IP addresses.  Consider the following:

('OA IP is: ', u'1')
Now Processing OA 1.
Cannot connect to OA: 1.
[Errno None] Unable to connect to port 22 on 0.0.0.1

Here are some code snippets
def automatic_mode():
    enclosure_results_lst = []
    try:
        enclosures_lst = get_chassis_data() 
        # Function pulls IP addresses from another systm
        # Function return a Python list.  Example below
        # enclosures_lst = ['10.0.0.1', '10.0.0.1', 

Open in new window

0
Free Tool: Port Scanner
LVL 9
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

i got a list of lists in ,
outerlist = [['name Belgian Waffles', 'price $5.95', 'description Two of our famous Belgian Waffles with plenty of real maple syrup', 'calories 650']
['name Strawberry Belgian Waffles', 'price $7.95', 'description Light Belgian waffles covered with strawberries and whipped cream', 'calories 900']]

The requirement is  to write the list to a csv file in the format

name                                                 description                                                                                                             price           calories      
Belgian Waffles                                Two of our famous Belgian Waffles with plenty of real maple syrup        $5.95         650             
Strawberry Belgian Waffles        Light Belgian waffles covered with strawberries and whipped cream        $7.95         900             
 

I tried the following python code

l = []

for item in outerlist:
    d = {kv.split()[0]:' '.join(kv.split()[1:]) for kv in item}
    l.append(d)
print (l)                     #----> returns random order

keys = l[0].keys()

with open(csvFileDir ,'w', newline = '') as o:
    writer = csv.DictWriter(o,fieldnames=keys)
    writer.writeheader()
    writer.writerows(l)

I am able to parse the same to a csv file , but the order returned is random .

What should I do to make sure the order returned is the same as the order given as input .

I tried OrderedDict but it returned

ValueError: too many values to unpack …
0
ab= [['name Belgian Waffles', 'price $5.95', 'description Two of our famous Belgian Waffles ', 'calories 650'] ]

I would like to parse this list to an CSV file in the table format

Ex. :
name                       price                      description                                                    Calories
Belgian Waffles      $5.95                     Two of our famous Belgian Waffles         650


Note : List size may vary . The values can vary . No hard coding should be there
0
when select employee= administrator it work correctly but when select apart from administrator thenn i does not work. i use the following code:
@api.onchange('number_of_days_temp')
      def _half_day_allowed(self):

            date_from = self.date_from
            date_to = self.date_to
            current = self.env['hr_leave_rules.leave_rules'].search([(
                        'holiday_status_id','=',self.holiday_status_id.id)])
            if current.half_day_allowed == 'no':
                  self.number_of_days_temp = ceil(self._get_number_of_days(
                        date_from, date_to, self.employee_id.id))
                  return {'value':{},'warning': {
                        'title': 'Please note :',
                        'message': 'You are  not allowed to take half day leave !'
                        }}
Screenshot-from-2017-08-14-17-33-01.png
0
pip install twilio
works perfectly on a Pi2.   Just bought a new Pi3 with the latest NOOB.  
same version of python (2.7.9), same version of pip (1.5.6).  I keep getting the error:

TypeError: __str__ returned non-string (type Error)

Googling around, I checked and verified that
- no network issue, Chromium connects to https://pypi.python.org/simple/twilio/
- my date/time on the computer is correct
- some talk about --trusted-host=http://pypi.python.org/simple/ but that parameter is not valid on pip
- some talk about creating an /etc/pip.conf file and adding trusted-host=pypi.python.org but that makes no difference (assuming pip every reads that file...)

My guess is that it has something to do with the SSL certificates... but I have no idea how to solve it.  
sudo apt-get install libssl-dev did not help

Thoughts?
pip.log
0
Hi: Don't you just hate banks?
We have changed bank and I download all the data  for analysis.  Our new bank offers only csv format. No problem...EXCEPT that for direct debits and standing orders the text field has a comma inserted! It looks to me that the comma is inserted just prior to the word MANDATE.
Dopes anybody know how to write something in python that deletes (or replaces with a semi colon) a comma that appears just before the word MANDATE in a csv file?
Here is a snippet of the text field:
"DIRECT DEBIT PAYMENT TO XXXX PENSION REF 09999999991, MANDATE NO 9999"
See that stupid comma in the middle?
The text before the comma changes every time.

Thanks!
0
from flask.ext.api import FlaskAPI
from flask import request, current_app, abort
from functools import wraps

app = FlaskAPI(__name__)
app.config.from_object('settings')

def token_auth(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if request.headers.get('X-API-TOKEN', None) != current_app.config['API_TOKEN']:
            abort(403)
        return f(*args, **kwargs)
    return decorated_function

@app.route('/predict', methods=['POST'])
@token_auth
def predict():
    from big_model import model
    item = request.data.get('item')
    total_predictions = request.data.get('num', 100)
    if not item:
        return []
    return model.predict(str(item), total_predictions)


@app.route('/train')
@token_auth
def train():
    from big_model import model
    data_url = request.data.get('data-url', None)
    model.train(data_url)
    return {"message": "Success!", "success": 1}

if __name__ == '__main__':
    app.debug = True
    app.run()
0
I installed Visual Studio Code & I would like to program in python when I go to compile my code I get these error messages

errorI am confused what to add.
When it goes to that point, I do not know what to put in.
Can someone help.

I debug my code, and press run and I get those 2 error messages, but the code successfully runs.
0
For a school project, I've been tasked with setting up an attendance-taking program. I've done some research and have come to a conclusion: I need some help.

I've got a bit of a plan but I'm not sure if it will work since I've got next to no experience in this type of thing. I want to use a barcode scanner to scan a specific barcode for a student and then input that into some sort of python program and log attendance.

I'm confident I can write the python code but I don't know how to connect a barcode scanner to the IDE, I'm also not sure which IDE to use.  I have considered trying to use Arduino connected to a webcam (or something similar).

Nevertheless, I need some expert advice, so any input will be met with extreme gratitude since I've been stuck at this point for weeks.
Thanks in advance.
0
Hello Python Individuals,

I need to connect to the Lotus Notes and do some operations (Send/Receive mail with Attachments).
However, I am not able to get past even the ‘Dispatch’ step:

import os, sys, stat, shutil
import os.path
import string
from configparser import SafeConfigParser
import tempfile
import logging
import getpass
import time
from win32com.client import makepy
from win32com.client import Dispatch
import win32com.client
import pywintypes
import smtplib
import csv # imports the csv module
makepy.GenerateFromTypeLibSpec('Lotus Domino Objects')
makepy.GenerateFromTypeLibSpec('IBM Notes Automation Classes')
Session = win32com.client.Dispatch('Lotus.NotesSession')

Open in new window


This rises an exception (Traceback)
File ..\Anaconda3\Lib\site-packages\win32com\client\dynamic.py in _GetGoodDispatch
IDispatch = pythoncom.connect(IDispatch)
Pywinttypes.com.error: (-2147221021, ‘Operation unavailable’, None, None)

During handling of above exception, another exception occurred:

Traceback
File My file
Session = win32com.client.Dispatch('Lotus.NotesSession')
File ..\Anaconda3\Lib\site-packages\win32com\client\__init__.py in Dispatch
  dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File ..\Anaconda3\Lib\site-packages\win32com\client\dynamic.py in _GetGoodDispatchAndUserName
      return (_GetGoodDispatch(IDispatch, clsctx), userName)
File ..\Anaconda3\Lib\site-packages\win32com\client\dynamic.py in  _GetGoodDispatch
      IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
Pywinttypes.com.error: (-2147221164, ‘Class not registered’, None, None)


Thanks in advance for any ideas or aid.

Doug
0
On Demand Webinar: Networking for the Cloud Era
LVL 9
On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

-------my code-----

import xml.dom
import xml.dom.minidom
doc = xml.dom.minidom.parseString('''
<root>
   <person id="01">
      <name> abc</name>
      <age>32</age>
      <address>addr123</address>
      <siblings>
        <name></name>
        <name></name>
      </siblings>
   </person>
   <person id="02">
      <name> def</name>
      <age>44</age>
      <address>addr456</address>
      <siblings>
        <name></name>
        <name></name>
        <name></name>
      </siblings>
   </person>
</root>

''')


def innerHtml(root):
    text = ''
    nodes = [ root ]
    while not nodes==[]:
        node = nodes.pop()
        if node.nodeType==xml.dom.Node.TEXT_NODE:
            text += node.wholeText
        else:
            nodes.extend(node.childNodes)
    return text

for statusNode in doc.getElementsByTagName('person'):
    for childNode in statusNode.childNodes:
        if childNode.nodeType==xml.dom.Node.ELEMENT_NODE:
            print("{}={}".format(childNode.nodeName, innerHtml(childNode)))

-------------output i got is------------------
name= abc
age=32
address=addr123
siblings=
                     
name= def
age=44
address=addr456
siblings=

---------but expected output should be in tableformat-----
i need to get the person id attribute also...pls answer

person id         name         age      address
01                abc          32      addr123
02                def          44       addr456
0
Basically I am an Electrical Engineer. I am doing estimation & Design.

I am repeating the same work again and again. I decide to automate my boring works

From google i found Python to make the script.

Since I need output in .xls & .dxf i selected xlxwriter and dxf write module.

To create user interface i selected Pyqt..

But I got stuck how to convert this all files as a single file. So i can distribute the same company with commercial befit.

Can you please advice the next step..
0
input xml can be any. It is dynamic file. so there is no pre determined tags. it should be created depending on the input xml file.

And i need the code for following requierments.

Parse XML file to create a tree of objects
   - create an object for each xml element
   -object mainly contains xml element name, value, attributes, list of sub elements where each member in the list is another xml element object
   - a function to create object tree
  - a function to iterate
0
I want to import a huge number of very small text files (content is 1 line per file) parse the line and convert it to another text file using delphi. Using the simplest assign(f) etc approach will take several weeks to execute. The bottleneck might probably be the opening/closing of each file. Is there any other way of doing this a lot faster?  maybe using another scripting language? which one?
0
how to calculate the time difference between date-time have single field only in python. it is like :-i have one row and column which field name is puch time here is the list of date-time 07/13/2017 18:41:24,       07/13/2017 18:57:31, 07/13/2017 17:29:27 now calculate time between 07/13/2017 18:41:24,       07/13/2017 18:57:31 in a and 07/13/2017 18:57:31, 07/13/2017 17:29:27  in b.
0
hi,

i have a massive python project without Readme file. what is the best way to understand how to run that project?

many thanks.
0
I have a cheap Microsoft RFID reader from eBay.  I am using 125mhz chips.  I have a Python program that writes the card number and date to a text file on a server.  Groups of people scan their card and it writes each number and date on a new line in this text file.  Sometimes however, it writes a string of numbers all on the same line with just one date at the end.  Could the problem be that a delay should be written into the Python program between reading the card and writing it - say 100ms?
Each entry should be on a new line and look like this:

0268340542, , , , 11:28:41, 2017-06-07

I get a lot like the above and then it does the following:

026835201202683520560268339729026833971602683537820268339746026835368202683500370268351993026833974102683397410268350159026835013402683375290268350089026835203902683501050268350105, , , , 09:25:48, 2017-06-12

So instead of recording each RFID card it puts them all into the one line with one , , ,  , time and date at the end.
Someone has suggested that it is parallel writing and to lock the file between writes but I don’t know how to do this.
The code is below:
0
Hello everybody,
i wanna know what's the use of "yield" in python and what differentiates  it from "return"
0
We are using ELK(Elastic search, logstash, and Kibana) for our log management. Everytime I will export the setting from kibana UI from Management--->Save Objects--->Export Everything. For demo, one can checkout the url: Kibana Demo

cURL
I want to automate this export process with some scripting on linux. I tried CURL but the header/payload data looks to be dynamic and might have to update frequently. I want to try some web scraping techniques with some web automation tools like Selenium and pythion.

Selenium Webdriver
I tried to record this export action with Selenium IDE and from the IDE I exported the test plan/case into pythonkibana_python.py . As we click on Export Everything button on Kibana, a firefox window opens asking where to save. This action is not handled by selenium, meaning download file is not supported by selenium.

So, I'm looking for some scripting to export the json(Export Everything) file from Kibana UI and it mush be Headless as I would be scheduling this script in linux server. To be headless, I also tried phantomjs, but even this doesn't support file download.

Simply, I just want a script to automate clicking export everything button on kibana and want it be saved in a file. Please share your thoughts or any idea,  i'm trying this for days...
0
Free Tool: IP Lookup
LVL 9
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Hi.
I converted  dex reader code sample  from the python  example Python version  to java but i am failing on   master handshake (after slave in master mode).
Failed on State 3 - Sending master key.
Have some one experience to read audit data from DEX  vending machine from android Bluetooth or DEX  cable.
File Provided.
My task: Allows the user to read DEX from a vending machine using a Bluetooth DEX device.
DexReader.java
0
So i'm trying to parse some xml with ElementTree, but it's got smileys in what seems to be UTF-16 decimal.
it's got this `&#55357;&#56835;` in it but says it's UTF-8 in the <?xml?> tag.


How do I decode UTF-16? Is that the right question to ask?
0
Update: Found my own solution, but would prefer a tal: solution if there is instead of javascript

I am running Plone 5, and have created two content types:
1. Purchase Order
2. Purchase Order Details.

I have created a purchase order custom page template which includes information about the selected Purchase Order (Title/Summary), and a table with the Purchase Order Details (Item Description/Item Summary/Quantity/Cost/SubTotal) as pictured below.  I am struggling with how to calculate the total of the purchase order in this scenario.  In the code below I only initialize a value of 0, but need to add the code to increase the total after every iteration of the purchase order details.

Purchase Order Content Type Page Template
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
      xmlns:tal="http://xml.zope.org/namespaces/tal"
      xmlns:metal="http://xml.zope.org/namespaces/metal"
      xmlns:i18n="http://xml.zope.org/namespaces/i18n"
      lang="en"
      metal:use-macro="context/main_template/macros/master"
      i18n:domain="plone">

<metal:css fill-slot="style_slot">
<style type="text/css">
    <!-- Replace this with your views' custom CSS -->
</style>
</metal:css>

<metal:javascript fill-slot="javascript_head_slot">
<script type="text/javascript">
jQuery(function($) {
    // Replace this with your view's custom onLoad-jQuery-code.
});
</script>
</metal:javascript>

<body>

<metal:content-core fill-slot="content-core">
    <metal:content-core 

Open in new window

0
hi,

how do i install and run a python project from getlib on my mac computer?

thanks.
0
I have a cheap Microsoft RFID reader from eBay.  I am using 125mhz chips.  I have a Python program that writes the card number and date to a text file on a server.  Groups of people scan their card and it writes each number and date on a new line in this text file.  Sometimes however, it writes a string of numbers all on the same line with just one date at the end.  Could the problem be that a delay should be written into the Python program between reading the card and writing it - say 100ms?
0
Hi everyone,

So I've spent the past week reading and trying to understand the python language and more importantly the CherryPy web framework.
To be honest Im getting no-where quickly...

What I'm trying to do is simply build a frontend to a Raspberry Pi project I've been developing.
The CherryPy web framework seems perfect for this as it is small and contains its own web server that would suite my needs perfectly.

An admin user attaches to the Raspberry PI AP and is immediately directed to a webpage (This I have solved quite easily).
The webpage is presented by the CherryPy web server.

I have an index.html which it returned from my CherryPy script.

import os, os.path, sys
import cherrypy

# Configuration file to access server over network and define ports
cherrypy.config.update("server.conf")

class menu(object):
    @cherrypy.expose
    def index(self):
        return open('index.html')

(Fairly simply until now I know)

What I would like to do is have buttons on my index.html that can be pressed and return os.system('mkdir boom')  (obviously my system commands will be a little more than this.. They will start and stop services.

The buttons will eventually be toggle switches, so going to the page will need to return the current status of the running process. Red if the process is not running and Green if it is running. I think I need to be interacting with jquery on my index.html page to achieve this...

This whole area is new to me and …
0

Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.