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

Following are code snippets from python 3.6 standard library logging module, filename __init__.py

On line 1732, class RootLogger gets instantiated.  But on line 1733, what is Logger.root ?  dot notation is used with object name, not class name ?
On line 1734, what is Logger.manager ?  Again, why dot notation is used with class name ?

#--------------------------------------------------------------------------- 
1250 #   Logger classes and functions
1251 #---------------------------------------------------------------------------
1252 
1253 class Logger(Filterer):
1254     """
1255     Instances of the Logger class represent a single logging channel. A
1256     "logging channel" indicates an area of an application. Exactly how an
1257     "area" is defined is up to the application developer. Since an
1258     application can have any number of areas, logging channels are identified
1259     by a unique string. Application areas can be nested (e.g. an area
1260     of "input processing" might include sub-areas "read CSV files", "read
1261     XLS files" and "read Gnumeric files"). To cater for this natural nesting,
1262     channel names are organized into a namespace hierarchy where levels are
1263     separated by periods, much like the Java or Python package namespace. So
1264     in the instance given above, channel names might be "input" for the upper
1265     level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
1266     There is no arbitrary

Open in new window

0
OWASP Proactive Controls
LVL 19
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

Looking at Python for the first time … going through these tutorials

I'm running Python via SPSS Statistics (Python 3.4.3 Shell) and got this error which is entered directly from the tutorial:
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 55
>>> if x < 0:
	x = 0
	print('Negative changed to zero')
	elif x == 0:
		
SyntaxError: invalid syntax
>>> 

Open in new window


In Anaconda I get this error:
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 55
>>> if x < 0:
... x = 0
  File "<stdin>", line 2
    x = 0
    ^
IndentationError: expected an indented block
>>>

Open in new window

And if I press the Indent key, Anancoda throws up on me ...

So not sure what I'm doing wrong right out of the gate ...

Also, is there a recommended IDE for Python?
0
Hi all i am currently going made trying to move my python project to a linux server,
1. i have got the mysql  database one there
2. i am trying to install all on the modules but having some issues i am trying  to get pip3 install parse , it tells me it works but it still comes up with a error when i run the python
3. i tried sudo pip3 install urllib
Collecting urllib
Exception:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 353, in run
    wb.build(autobuilding=True)
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 278, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File …
0
Hi all i dont know if there is a way but i khave a site i have just taken over and it is still running windows 8.1 and i need to upgrade them all to 10, the issues is its over two offices and i cant be bothered driving out to them all, is there a script, powershell, batch, pythen, that i can run to get the pc to do it
0
I'm using python version 3.6.8.  

I'm looking at large python project.  In beginning of __init__.py, there is following statement:

Logger = logging.getLoggerClass()

Open in new window

Is getLoggerClass a class?  Is above code instantiating this class?
What is the purpose of above code?
0
HI,

I'm trying to modify below python script o produce nice tabular output. (Right now its not in a readable format)

Thanks in advance

Script source:
https://github.com/hjacobs/aws-cost-and-usage-report/blob/master/aws-cost-and-usage-report.py

Current output
./aws-cost-and-usage-report.py
TimePeriod	LinkedAccount	Service                                 	Amount	Unit	Estimated
2019-11-08 	 21212121212121	AWS CloudTrail 	 	 	                       0.153943 	 USD 	 False
2019-11-08 	 21212121212121	AWS Config 	 	 	                          9.213 	 USD 	 False
2019-11-08 	 21212121212121	AWS Direct Connect 	 	 	                   0.2797877163 	 USD 	 False
2019-11-08 	 21212121212121	AWS Key Management Service 	 	 	                   1.4141780112 	 USD 	 False
2019-11-08 	 21212121212121	AWS Lambda 	 	 	                   0.0804225759 	 USD 	 False
2019-11-08 	 21212121212121	Amazon DynamoDB 	 	 	                   0.3836161225 	 USD 	 False
2019-11-08 	 21212121212121	Amazon EC2 Container Registry (ECR) 	 	 	                   0.0783308328 	 USD 	 False
2019-11-08 	 21212121212121	Amazon EC2 Container Service 	 	 	                              0 	 USD 	 False
2019-11-08 	 21212121212121	EC2 - Other 	 	 	                   6.8639388761 	 USD 	 False
2019-11-08 	 21212121212121	Amazon Elastic Compute Cloud - Compute 	 	 	                  73.1890902202 	 USD 

Open in new window

0
Sample csv file:

X            year
120           2010
120           2011
120           2012
121           2010
121           2011
132           2010
132           2012
145           2010
145           2011
145           2012


We have some column named X in a csv file. There are same values of X for 3 years, some are missing from either of the year like 121 is not for 2012. I want to check if all values in 2010 are there in other years. If no, then I wanted to list those X values. Here, the output should be

X      year
121   2012
132  2011
0
Bitbake is a python program. Following guide shows how to setup BitBake.
https://a4z.bitbucket.io/docs/BitBake/guide.html

Form Linux command prompt, I invoke bitbake by simply typing bitbake.  Since the location of this program is in PATH variable, bitbake runs. But how does python compiler know it's a python program.  Aren't python programs required to have .py extension?

filename:  bitbake
#!/usr/bin/env python3
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# Copyright (C) 2003, 2004  Chris Larson
# Copyright (C) 2003, 2004  Phil Blundell
# Copyright (C) 2003 - 2005 Michael 'Mickey' Lauer
# Copyright (C) 2005        Holger Hans Peter Freyther
# Copyright (C) 2005        ROAD GmbH
# Copyright (C) 2006        Richard Purdie
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import os
import sys

sys.path.insert(0, 

Open in new window

0
Hi all i am trying to setup my ubuntu server so i can run my python scripts and when i try to install mysql-client or mysql for python i am getting a error
Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-nwk7rejx/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-10shw23u-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-nwk7rejx/mysqlclient/

i have  tried good old google and all the ones i have found on there to try didnt work any help would be great
0
Hi Experts,

see python code below. i have converted to C#. but i'm getting bad request error.
Same way i did for other request all are working fine.But i think something problem with Date parameters.
Any idea where i'm doing mistake?

Python code is wworking fine
Python code
import requests

url = "https://api.bamboohr.com/api/gateway.php/test/v1/time_off/requests/"

querystring = {"start":"2019-12-01","end":"2020-01-15"}

headers = {
    'accept': "application/json",
    'authorization': "Basic 4YWNhYzUxMjY3MmFlYWIxNzQ3MzZjMDY0ZA=="
    }

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)

Open in new window


See my C# Code
 var request = new RestRequest(whourl, Method.GET);
            request.AddHeader("Content-Type", "application/json");
           
            request.AddParameter("start","2019/12/01");
            request.AddParameter("end","2020/01/15");
            
            IRestResponse response;
            RestClient _iRestClient = new RestClient(Config.ApiUrl);
            _iRestClient.Authenticator = new HttpBasicAuthenticator(Config.ApiKey, "x");
            try
            {
                response = await _iRestClient.ExecuteTaskAsync(request);
            }
            catch (Exception ex)
            {
                throw new Exception("Error executing Bamboo request to " + whourl, ex);
            }

Open in new window


Response URI like this

{https://api.bamboohr.com/api/gateway.php/abc/v1/time_off/requests/?start=2019%2f12%2f03&end=2020%2f01%2f05}


Any idea much appriciated
0
C++ 11 Fundamentals
LVL 19
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

working with Python Dictionary

I have the code below :
message=input(">")
words=message.split(' ')
print (words)
emoh={
    ":)":"😂",
    ":(":"😒"
}
output=""
for word in words:
    print(word,word,word,word,word)
    print (emoh.get(word))
    output+= (emoh.get(word,word))
print (output)

Open in new window


When I run it , I get the result below:

p
The question is why I am getting the "None" ?

Thank you
1
I'm attempting to run this python script

In the scrapy.cfg points to this page  to install scrapy like so
pip install scrapyd

Open in new window


Which I've done however running the script using the example I get this error

Scrapy.JPG
BTW I've set up unbuntu 18.4 in virtualbox this came with python preloaded
0
from requests_html import HTMLSession
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="**",
  database="flightdata"
)

mycursor = mydb.cursor()

# create an HTML Session object
session = HTMLSession()

# Use the object above to connect to needed webpage
resp = session.get("https://www.adelaideairport.com.au/flight-information/flight-search/?flt_no=&carrier=All&city=&dte=Current&leg=Departures")

# Run JavaScript code on webpage
resp.html.render()


airline_spans = resp.html.find('.SearchResultFlightListRow')
print (airline_spans)
airline_list = [span.text.split('\n') for span in airline_spans]

for flight in airline_list:
    if len(flight) == 7:
        flightno, From, to, scheduled, estimated, gate, status = flight
        print ("This is a " + estimated)
        if estimated == "":
            print (" currently no dely ")
            print ("This is a " + estimated)
            estimated = 'IDEL'
        print (f'Flight no {flightno} from  {From} to {to} is scheduled to depart at {scheduled} from gate {gate} and flight status is {status}')

    elif len(flight) == 6:
        flightno, From, to, scheduled, estimated, gate = flight
        status = 'IDEL'
        print ("This is a " + estimated)
        if estimated == "":
            print (" currently no dely ")
            print ("This is a " + estimated)
            estimated = 'IDEL'
        print (f'Flight no {flightno} …
0
Hi I need to test a python script

Are there any Virtual Machines available that has python pre-installed
if not What would be the best OS to run Python

It would need to run on Win 10 host with access to host  HDD & the internet
0
Bitbake is a python program. It was downloaded from:  https://github.com/openembedded/bitbake
bitbake 1.40.0 branch was selected for download.

What instantiated class ConfigParameters(object)?  I see that __init__ or constructor was executed but exactly what python code instantiated this class?


object created
filename:  cookerdata.py
class ConfigParameters(object):
    def __init__(self, argv=sys.argv):
        self.options, targets = self.parseCommandLine(argv)
        self.environment = self.parseEnvironment()

Open in new window


filename:  bitbake
if __name__ == "__main__":
    if __version__ != bb.__version__:
        sys.exit("Bitbake core version and program version mismatch!")
    try:
        sys.exit(bitbake_main(BitBakeConfigParameters(sys.argv),
                              cookerdata.CookerConfiguration()))

Open in new window

0
BitBake is a Python Program.  I downloaded BitBake from  https://github.com/openembedded/bitbake.  I selected branch version 1.40.0 and downloaded the zip.  
At least some of the source code is in bitbake-1.40.0/bin  and  bitbake-14.0.0/lib folders.

I can insert print statements to navigate source code.  Is there alternate way to navigate python program such as bitbake?
0
Hi all i am new to the site i am trying to get a python script i am doing working and i am getting a error AttributeError: 'list' object has no attribute 'find_all'

I have attached the code , i would like to get all the different fulds in to different elements so i can save them to a mysql database

#erth Airpirt DEPARTURE IMPORT SCRIPT
#CREATED BY ADBY IT AND MEDIA SOLUTIONS
#VERSION 1.1
#DATE 25 NOVEMBER 2019
#UPDATED 26 NOVEMBER 2019
#AUTHOR ADAM R WOLARCZUK


from requests_html import HTMLSession # import HTMLSession from requests_html
import requests
from requests_html import HTMLSession
from bs4 import BeautifulSoup
import mysql.connector


session = HTMLSession() # create an HTML Session object
resp = session.get("https://www.adelaideairport.com.au/flight-information/flight-search/") # Use the object above to connect to needed webpage
resp.html.render() # Run JavaScript code on webpage


#page = requests.get("https://www.adelaideairport.com.au/flight-information/flight-search/")
soup = BeautifulSoup(resp.html.html, "lxml")
flights = resp.html.find("SearchResultFlightListTable")
flight_items = flights.find_all(class_="row")
flight = flight_items[0]
print(flight.prettify())
0
anaconda not starting in my ubuntu
curl -O https://repo.anaconda.com/archive/Anaconda3-5.2.0-Linux-x86_64.sh
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  621M  100  621M    0     0   854k      0  0:12:24  0:12:24 --:--:--  991k
python@python-VirtualBox:/tmp$ sha256sum Anaconda3-2019.03-Linux-x86_64.sh
sha256sum: Anaconda3-2019.03-Linux-x86_64.sh: No such file or directory
python@python-VirtualBox:/tmp$ ls
Anaconda3-5.2.0-Linux-x86_64.sh
config-err-80MCXE
ssh-bM5S1pofRzcW
systemd-private-869adb399f9b4bb29d1faede46df776f-apache2.service-WtkZd0
systemd-private-869adb399f9b4bb29d1faede46df776f-bolt.service-Gy1KOQ
systemd-private-869adb399f9b4bb29d1faede46df776f-colord.service-ueDFWp
systemd-private-869adb399f9b4bb29d1faede46df776f-fwupd.service-YzXstt
systemd-private-869adb399f9b4bb29d1faede46df776f-ModemManager.service-dB7it9
systemd-private-869adb399f9b4bb29d1faede46df776f-rtkit-daemon.service-53koIw
systemd-private-869adb399f9b4bb29d1faede46df776f-systemd-resolved.service-lmGjYY
python@python-VirtualBox:/tmp$ bash Anaconda3-2019.03-Linux-x86_64.sh
bash: Anaconda3-2019.03-Linux-x86_64.sh: No such file or directory
python@python-VirtualBox:/tmp$ sudo bash Anaconda3-2019.03-Linux-x86_64.sh
[sudo] password for python:
bash: Anaconda3-2019.03-Linux-x86_64.sh: No such file or directory
python@python-VirtualBox:/tmp$ conda list
conda:
0
After hitting submit button on my forum in django, i want to change the value of my field after the post request . The field is status, basically i want to pass a string into the field that says " In Session". Here is my views.py .


@login_required
def K8_Points(request):
   if request.method == 'POST':
      form = K8PointsForm(request.POST)
      if form.is_valid():
         status = "In Session"
         form.save()
           
   else:
     form = K8PointsForm()   
     return render(request, 'points/k8_points.html', {'form': form})     

Open in new window



Models.Py


class K8Points(models.Model):
    dayid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    date = models.DateField(default=timezone.now) 
    teacher_class= models.ForeignKey(TeacherClass, on_delete = models.PROTECT, default = "")
    week_of = models.IntegerField(default=weeknumber)
    day = models.CharField(max_length= 10)
    status = models.CharField(max_length= 10, default = "", blank = True)

Open in new window

0
PMI ACP® Project Management
LVL 19
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

I have a field in my database that is displayed on my form in Django that i want to be just readonly. How do i do that ?


Here is my a section of my HTML page.

{% extends 'base.html' %}

{% load crispy_forms_tags %}
{% load static %}
{% block content %}

<br>
<h2>{% load static %}
<img src="{% static 'forms/star.png' %}" alt="chain" height="62" width= "62">  K-8 School Points</h2>
<br>
<br>
<div class = "container">
 <div class= 'row'>
  <div class="col-4"> 
<p> Recording Data as User : {{user.username}} </p>
  </div>
</div>

 <div class= 'row'>
  <div class="col-2"> 
<p>{{form.status|as_crispy_field }}</p>                                <------------This is the field i need to be readonly 
  </div>
</div>
<form method="POST">
    {% csrf_token %}
 <!-- Start Date -->

Open in new window

0
Attached is a section from "BitBake User's Manual" that uses inline Python variable expansion to set variables.
Please explain in detail how the DATE variable is set.
python.PNG
0
I'm trying to set one of my fields equal to a variable.

The field in my models week_of I want to equal to the variable I created . The variable in my Views.py titled weeknumber should be week_of = weeknumber is what I’m trying to accomplish.


In theory the field in week_of is suppose to extract the current week number and auto input it. So i can be doing this completely wrong, deft need guidance. Thank you all so much for the help !

views.py

def K8Points (request):
 if request.method == 'POST':
    form = K8PointsForm(request.POST)
    weekNumber = date.today().isocalendar()[1] 
    if form.is_valid():
        points = form.save()

Open in new window


models.py

class K8Points(models.Model):
    date = models.DateField(default=timezone.now) 
    teacher_class_id = models.ForeignKey(TeacherClass, on_delete = models.PROTECT, default = "")
    student_id = models.CharField(max_length=50, default = "")
    total = models.IntegerField()
    week_of = models.DateField()
    day = models.CharField(max_length= 10, choices= DAY_OF_THE_WEEK)

Open in new window

0
resim.pngI have a text file.
I want to get some special parts from within this text.
I indicated the fields under the red line.
I tried to write code but couldn't get it.
The text inside  in 'son.txt'
import re
import csv
f = open('son.txt', encoding='utf-8', errors='replace')
xxx=f.read()
sonuc=re.findall(r'<<(.*)>>(.+).$',xxx)
for i in sonuc:
     print(i)

Open in new window

I showed the fields I want in the picture.==>>Resim.png
How can I get?
son.txt
0
Import Netmiko to Pycharm fails

I have installed Netmiko  as shown below:
C:\Users\user>pip show netmiko
Name: netmiko
Version: 2.4.2
Summary: Multi-vendor library to simplify Paramiko SSH connections to network devices
Home-page: https://github.com/ktbyers/netmiko
Author: Kirk Byers
Author-email: ktbyers@twb-tech.com
License: MIT
Location: c:\users\user\appdata\local\programs\python\python38\lib\site-packages
Requires: paramiko, pyserial, scp, textfsm, setuptools
Required-by:

C:\Users\user>

Open in new window


However I still cannot import  Netmiko to Pycharm

n
0
Use PIP in Python installed on Windows.

I have python 3.8 installed , I would like to install PIP.
Any help on how to get it installed? does it require download ? if so then from where?

Thank you
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.