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

I want to read a file, and look for line A, and then look for line B, and then look for line C. Currently I have something like:

with open(infile, 'r') as inf:
    for line in inf:
        #do something with each line until we come to line A
        if line == A:
            #we found line A. Keep reading lines until we come to line B
            #do something with each line until we come to line B
            if line == B:
                #we found line B. Keep reading lines until we come to line C
                #do something with each line until we come to line C
                if line == C:
                    #Hooray!

Open in new window

Now I want to convert this to something nicer, like a state machine:
def initial_state()
    read lines from inf
        do something with each line until we come to line A
        if line == A:
            found_line_A()
            
def found_line_A()
    read lines from inf
        do something with each line until we come to line B
        if line == B:
            found_line_B()
            
def found_line_B()
    read lines from inf
        do something with each line until we come to line C
        if line == C:
            #Hooray!

with open(infile, 'r') as inf:
    initial_state()            

Open in new window

How can I read lines from the same input file inf in each of the three functions above?
0
Fundamentals of JavaScript
LVL 12
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

HI

If I open jupyter notebook  something.jpynb , it opens as html marked up file vs a neat boxes in jupyter notebook page. How do I get this to work? I have anaconda installed.
 

{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Your name:\n",
    "\n",
    "<pre> Enter your name here</pre>\n",
    "\n",
    "### Collaborators:\n",
    "\n",
    "<pre> Enter the name of the people you worked with if any</pre>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import matplotlib\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Markdown referece can be found here:\n",
    "
0
This python 3 script won't print.  Why?

class Fish:
    def __init__(self, first_name, last_name="Fish",
                 skeleton="bone", eyelids=False):
        self.first_name = first_name
        self.last_name = last_name
        self.skeleton = skeleton
        self.eyelids = eyelids

    def swim(self):
        print("The fish is swimming.")

    def swim_backwards(self):
        print("The fish can swim backwards.")
        
class Clownfish(Fish):
    
    #has own special method to live with anemone

    def live_with_anemone(self):
        print("The clownfish is coexisting with sea anemone.")
                # now create a Clownfish object

    casey = Clownfish("Casey")
    print(casey.first_name + " " + casey.last_name)
    casey.swim()
    casey.live_with_anemone()

Open in new window

0
I am trying to put this function in node-red. While testing on python its work on raspberry pi - serial port perfectly. Currently i wanted to try on node-red via raspberry pi too.

#rpi serial connections
#Python app to run a K-30 Sensor
import serial
import time
ser = serial.Serial("/dev/ttyS0",baudrate =9600,timeout = .5)
print " AN-137: Raspberry Pi3 to K-30 Via UART\n"
ser.flushInput()
time.sleep(1)
for i in range(1,21):

 ser.flushInput()
 ser.write("\xFE\x44\x00\x08\x02\x9F\x25")
 time.sleep(.5)
 resp = ser.read(7)
 high = ord(resp[3])
 low = ord(resp[4])
 co2 = (high*256) + low
 print "i = ",i, " CO2 = " +str(co2)
 time.sleep(.1) 

Open in new window

0
I am writing ETL scripts using PySpark in AWS Glue. I have a few issues that I am trying to tackle. My source and target databases are Oracle 12c Standard.

1 How to capture incremental updates in the pyspark dataframe?
2 How to update existing record or insert new records in database in the incremental fashion?
3 Is it possible to perform above tasks using python alone instead of pyspark ?
0
i tryed to run code but these errors message


Traceback (most recent call last):
  File "/Users/wesleykelly/Desktop/tensor flow.py", line 2, in <module>
    import input_data
ImportError: No module named input_data
[Finished in 0.1s with exit code 1]
[cmd: ['/usr/bin/python', '/Users/wesleykelly/Desktop/tensor flow.py']]
[dir: /Users/wesleykelly/Desktop]
[path: /anaconda3/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin]
0
Is there a way to programmatically create a signed URL to a file in a AWS S3 bucket that will expire in a few minutes and will only allow a specific client IP Address?  I want to do this in Python so if you can send me Python specific links or examples, it would really help!
0
Dear experts,

In the recent past I have been inquiring or seeking your expert guidance on pursuing a career in Financial Engineering.
I have now reached the stage of working on objects in C++. Once I am thorough with C++ and after having worked on ‘Introduction to C++ for Financial Engineers’ by Daniel J Duffy, I plan to do a project work.
This project work will be done by me while I am in leave.
Can I request if anyone can guide me on selecting a project on Python/C++?
Which platform will be robust for this purpose?
Is there a book I can purchase and practice? Can I use the knowledge I gain by practicing this book in my interview process?

Kindly guide me.
0
With Python I can bind events and functions. This following piece of code calls a  function save everytime I press Ctrl and s key:
 root.bind('<Control-s>',save)

Open in new window

How can I bind pressing Ctrl + Shift + S with a function using  tkinter?
this doesn't work:
root.bind('<Control-Shift-s>',save)

Open in new window

0
I am running a Python CGI script from web browser to collect some data from a network device and at the moment the network device ip address is static.

  <ul>
          <li><a href="http://172.17.0.2/cgi-bin/info.cgi" target="_blank">Device Facts</a></li>
          <li><a href="http://172.17.0.2/cgi-bin/arp.cgi" target="_blank">Device Arp Table</a></li>
          <li><a href="http://172.17.0.2/cgi-bin/mac.cgi" target="_blank">Switch MAC Table</a></li>
          <li><a href="http://172.17.0.2/cgi-bin/lldp.cgi" target="_blank">lldp Neighbors</a></li>
         </ul>

Open in new window


Here is the CGI script

#!/usr/bin/python
print "content-type: json\n\n"
import json
from napalm import get_network_driver
driver = get_network_driver('ios')
hub2 = driver('10.0.0.120', 'admin', 'admin')
hub2.open()

ios_output = hub2.get_facts();
print json.dumps(ios_output, indent=5);
hub2.close()

Open in new window


Now i want the ip address to be user input, which then used as a variable in above mentioned python code. as an ip address.

Thank you
0
Starting with Angular 5
LVL 12
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

I have read in an image using python's gdal module and converted it into an image with a black background (value = 0) and a few clusters of white pixels (value = 1). I would like to cluster these white pixels using DBSCAN but most of the documentation/examples I read about deal with xy values on a table. Problem is that I have no idea how to extract the pixel locations per cluster. Is there a way to get a x-y tuple of pixel locations out of DBSCAN while feeding it an numpy array of shape (#xpix, #ypix)?
0
When using pymysql, is there a way to connect to MySQL database using a login-path created with mysql_config_editor?
0
Dear Experts,

I have a Python code which surely works correctly running from the console in Anaconda (one of the Python IDE)

My target is to create from this .py file and .exe, for that installed PyInstaller and created the .exe.

However running that .exe there can be just seen a fast flashing on the screen (like the cmc Command Prompt window it seems) and the code stops who knows where, no any error message or information where stopped.

Could you please point out some possibilities, how to troubleshoot issues in such generated .exe file containing Python code?

Thanks in advance,
0
well hi

i have this code:
import winreg;


def get(name):


      registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,r"Keyboard Layout",0,winreg.KEY_READ);
      value = winreg.QueryValue(registry_key,name);

      return value;

print(get("Keyboard"));

Open in new window


But an error is occured every time i run the programm:FileNotFoundError:[WinError] 2 . My error is when i use string "Keyboard" as a variable to my method:get(name);
0
Website Developer/ Designer with Python Experience Needed!

Looking for a Website Developer/ Designer to use as needed for updating/ editing website created using Python. I need to person to be available regularly as needed over the next 6-12 months. Hourly pay will be negotiated once I know you can do the job.
0
Can python do everything powershell can do?
0
Is experts exchange good for python help?
0
Dear Experts,

Could you please advise about a Python compiler, which would be able to create an .exe file from a .py one and which could be run on other computer without any dependency? (so without the need of installing Python and modules)

Basically I am aware of http://www.py2exe.org/ but would need a compiler which does not need installation on my computer, since not having administrative rights on Windows

Thanks in advance,
0
Hello All.
the python script below is going through a range of cells are removing comma's from cell values, it skips over empty cells, fine, but fails when a cell contains a numerical values like e.g 0 or 1342 etc... or the cell type is already an integer, it errors out. Can the code up set to aviod encountering those cell types?

AttributeError: 'int' object has no attribute 'replace'

from openpyxl.styles import numbers, fonts
wb = openpyxl.load_workbook(xlfile)
ws = wb['sheet1']

# No of written Rows in sheet
r = ws.max_row

# No of written Columns in sheet
c = ws.max_column

# Reading each cell in excel
for i in range(2, r+1):
    for j in range(2, c+1):
        v = (ws.cell(row=i, column=j).value)
        if v is None:
            break
        v = v.replace(',', '')
        print(v)
        v = int(v)
        print(type(v))
#https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/styles/numbers.html
wb.save(xlfile)
gc.collect()

Open in new window

0
CompTIA Cloud+
LVL 12
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Hi, I'm using openpyxl to format cells in excel from 'General' to other builtin formats. Although the script completes and states the format has been changed, when I try and open the excel file, excel pops with and error box, repair or cancel.

If the report option is selected, then another pop up prompts read only or exit. If I select read only Excel crashes.

Is the below the correct way to set number formats using openpyxl?

runfile('/.../test.py', wdir='/...python/...')
Reloaded modules:

Text
Number
Accounting
Currency

import openpyxl
wb = openpyxl.load_workbook(xlfile)
ws = wb['Sheet1']
ws['B1'].number_format = 'Text'
ws['B2'].number_format = 'Number'
ws['B3'].number_format = 'Accounting'
ws['B4'].number_format = 'Currency'
print (ws.cell(row=1,column=2).number_format)
print (ws.cell(row=2,column=2).number_format)
print (ws.cell(row=3,column=2).number_format)
print (ws.cell(row=4,column=2).number_format)
wb.save(xlfile)

Open in new window

Screen-Shot-2018-09-02-at-17.44.21.png
0
Hi, I'm trying to open an Excel file in python, go to a worksheet and append the format from general to number or currency for a cell range, but get the following error -


  File ".../python/html-table-parser/grapecore1.py", line 227
    incomesheet.append(cell_range, , money_format)
                                   ^
SyntaxError: invalid syntax

#Open workbook
from xlsxwriter.utility import xl_range
workbook   = xlsxwriter.Workbook(xlfile)

#Select worksheet
incomesheet = workbook.get_worksheet_by_name(Income)

# Add a number format for cells with money.
money_format = workbook.add_format({'num_format': '$#,##0'})
#money_format = workbook.add_format({'num_format': '[Blue]£#,##0.00_);[Red](£#,##0.00)'})

cell_range = xl_range(2, 1, 28, 4)
incomesheet.append(cell_range, money_format)

#Close workbook
workbook.close()

Open in new window

0
I have a Python/Django Web Application that I'm running on IIS (Windows Server 2016). This is on a dedicated machine and I've been thinking about putting this on a Production Web Server in order to save Server costs.

What are the implications, specifically from a Security perspective, of running Python, Django and FastCGI on a Windows machine? I've got the machine as an EC2 Instance that's locked to minimal ports using Security Groups and Windows Firewall, so I'm comfortable there.

Perhaps an Open Source expert can provide me with some flavor of the things I should be aware of from a Security viewpoint.

Thanks for your help.
0
I'm trying to extract a list of parameter names from a Python script. Here's an example of what I'm looking at
def foo(cmd
    ,pIncludeAll #BOOL
    ,pOrderByDisplayOrder #BOOL
    ) :
    try:
        ....

Open in new window

Currently, I'm using a Regex that grabs everything between the parentheses then just splitting on the comma. This doesn't work in the above case since there are comments after 2 of the 3 parameters. My split string ends up looking like this:
cmd
pIncludeAll #BOOL
pOrderByDisplayOrder #BOOL

Open in new window

What I need is a Regex that will produce a match result that contains each of the parameters without the comment like this:
cmd
pIncludeAll
pOrderByDisplayOrder

Open in new window

I know I need to delimit the Regex match on commas, whitespace, and pound signs. I just don't know how to write the expression so that it will return a proper match against an arbitrary number of arguments.
0
I have a working python script that scrapes tables. After the data is copied to an Excel file I would like to remove this particular value - '--' from all sheets in the Excel file and replaced with a zero value - '0'.
Whats the best way to do this using python?
Thanks

import urllib.request
import pandas as pd
import sys
import os
#import xlsxwriter
import openpyxl

sys.path.append('/Users/bhav\ 1/Documents/keepbak2/python')

#xlfile = 'countrydiedtest.xlsx'
xlfile = "/Users/bhav 1/Documents/dump/countrydiedtest.xlsx"

from html_table_parser import HTMLTableParser

Income = 'https://markets.ft.com/data/equities/tearsheet/financials?s=CWD:LSE&subview=IncomeStatement'
Balance = 'https://markets.ft.com/data/equities/tearsheet/financials?s=CWD:LSE&subview=BalanceSheet'
Cash = 'https://markets.ft.com/data/equities/tearsheet/financials?s=CWD:LSE&subview=CashFlow'
Historical = 'https://markets.ft.com/data/equities/tearsheet/historical?s=CWD:LSE'

#get website config Income
reqIncome = urllib.request.Request(url=Income)
fIncome = urllib.request.urlopen(reqIncome)
xhtmlIncome = fIncome.read().decode('utf-8')

#get website config Cash
reqCash = urllib.request.Request(url=Cash)
fCash = urllib.request.urlopen(reqCash)
xhtmlCash = fCash.read().decode('utf-8')

#get website config Balance
reqBalance = urllib.request.Request(url=Balance)
fBalance = urllib.request.urlopen(reqBalance)
xhtmlBalance = fBalance.read().decode('utf-8')

#get website config Historical
reqHistorical = 

Open in new window

0
Hello, Experts!

I am needing help with figuring something out.

I have a python script that reads a directory and gives me the last modified date. However, the output is not what I am looking for.

I get the time to be 24-hour format as opposed to US standard 12-hour format. What modifications do I need to make?

import os.path, time
print("Last modified: %s" % time.ctime(os.path.getmtime("test.txt")))
print("Created: %s" % time.ctime(os.path.getctime("test.txt")))

Open in new window

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.