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

Hi experts,

what is the best way to handle exception in below python3 subprocess scenario please?

I execute below line in my python script.['aws', 'ec2', 'start-instances', '--instance-ids', instance , '--output', 'table'])

Open in new window

could you suggest a best way to handle exception please? try/except?

Thanks in advance
A proven path to a career in data science
A proven path to a career in data science

At Springboard, we know how to get you a job in data science. With Springboard’s Data Science Career Track, you’ll master data science  with a curriculum built by industry experts. You’ll work on real projects, and get 1-on-1 mentorship from a data scientist.

In all my Java games, I have used code like :
public static int STAR_TYPE_RED_DWARF=1
public static int STAR_TYPE_WHITE_DWARF=2
public static int STAR_TYPE_BLUE_GIANT=3
public static int STAR_TYPE_SUPER_GIANT=4
and many more game object constants

What is the best way to replicate this in python, so these constants are automatically associated with its object when writing code?
I haven't seen anything like this yet

My requirement is exactly matching with below post from "StackOverflow". This code snippet works perfectly for only one excel file (workbook = xlrd.open_workbook('test.xlsx')) but I have more than 100 + excel files with same Sheet name across all the excel macro files.

Can someone please modify the code, which can create multiple files with different name

import csv
import xlrd

workbook = xlrd.open_workbook('test.xlsm')
for sheet in workbook.sheets():
    if == "Sheet_name_from_xlsm_file":
        with open('{}.csv'.format(, 'w') as f:
            writer = csv.writer(f)
            for row in range(sheet.nrows):
                out = []
                for cell in sheet.row_values(row):

Open in new window

Suppose I have 2 text files

Name, Age


Using Python 3, I’d like to produce a file like this.


The NA value is because A’s school is not in the second file and D’s age is not in the first file.
Hi Experts,
Would like to achieve below using python function. Could anyone help please

1. Python script (a function/def) to accept an argument. E.g. Instance_id1 or Instance_id2 or Instance_id3.
2.  Script to locate relevant instance section in the ini file. (sample file below).
3. Get always_on_start_time, always_on_finish_time, and current system time.
4. Then identify current time is not within start/finish time.
3.  If within, start/finish time, return true, else false.

We will have to further execute few more task based on above return string.

Thanks in advance.

Sample ini file



Open in new window


I am trying to read from a file and input the values from the file into my class. However, it is only taking the last line. How can I get it to do all of the lines in the file, which is five?

Text File :

[code]dataFile = open('apartmentData.txt')
for line in dataFile:
    lineData = line.split(',')
    apt1 = int(lineData[0])
    rent1 = float(lineData[1])
    rooms1 = float(lineData[2])
    baths1 = float(lineData[3])
apt_1= Apartments.Apartments(apt1,rent1,rooms1,baths1)
apt_2= Apartments.Apartments(apt1,rent1,rooms1,baths1)
apt_3= Apartments.Apartments(apt1,rent1,rooms1,baths1)
apt_4= Apartments.Apartments(apt1,rent1,rooms1,baths1)
apt_5= Apartments.Apartments(apt1,rent1,rooms1,baths1)


Open in new window

235        1375.0     3.0        2.0      
235        1375.0     3.0        2.0      
235        1375.0     3.0        2.0      
235        1375.0     3.0        2.0      
235        1375.0     3.0        2.0  

desired output:
231        1200.0     1.0        1.0      
232        1250.0     2.0        1.0      
233        1300.0     2.0        1.5      
234        1350.0     2.0        2.0      
235        1375.0     3.0        2.0  [/code]
Hi! The purpose of the program is to get the user to enter in there criteria for an apartment, and have all of the apartments that meet that criteria print out. However, my code only works to find the first apartment that meets the criteria and doesn't continue moving through the list. Any ideas on how to make this work while keeping my apartments class objects?

class Apartments(object):
    def __init__(self,aptNum, rent, rooms, bath):
            self.aptNum = aptNum
   = rent
            self.rooms = rooms
            self.bath = bath
    def getApt(self):
        return '{:<10} {:<10} {:<10} {:<10}'.format(self.aptNum,,self.rooms,self.bath)

Open in new window

import Apartments

apt_1= Apartments.Apartments(111,1000,1,1)
apt_2= Apartments.Apartments(112,2000,2,1)
apt_3= Apartments.Apartments(113,2500,2,2)
apt_4= Apartments.Apartments(114,3000,3,2)
apt_5= Apartments.Apartments(115,3500,3,3)


while True:
    rentInput=input('Enter maximum amount of rent: ')
    roomInput=input('Enter minimum number of bedrooms: ')
    bathInput=input('Enter minimum number of baths: ')
        val = int(rentInput)
        val2 = int(roomInput)
        val3 = int(bathInput)
        if val < 0:  
            print("Sorry, input must be a positive integer, try again")
        if val2 < 0:  
            print("Sorry, input must be a positive integer, try again")

Open in new window

Hi developers!
I am a software engineering student. I am now working on a project for my internship. I am receiving large JSON files with certain API ( I am working on JIRA's data ). Now I am working with python on those JSON files and getting pieces of information I need for my project. The problem is that what I am getting is so large and I need a lot of time to get everything I want. Is there a solution to accelerate the retrieval?
I have 5 Quiries which will pull the data from the oracle database and show the results

Now I am planning to work on a project like as below

1. JAVA program to use the Quries and pull those information and
2. Write into a spreadsheet with individual sheet names and
3. Finally send out an mail to the team with the link where I have copied the sheets.

Please share your thoughts

I am new to the Python program, and I am using a YouTube video, showing me how to download the program.  The instructor requests that I download PyCharm, which I did.  The problem, however, is that he uses a Mac version of the program, while I am using a PC version of the program.  The Apple menu shows a menu called "Preferences" option, which I don't see anywhere on any of the menus I have available on my PC.  Once there, the teacher requests that I change several settings, none of which do I see, since I don't see "Preferences".  These settings seem critical, and I am wondering if they exist elsewhere, in a more obscure menu I am not noticing.  

I have an attachment that shows the two environments: the Apple view from a screenshot in the video, and the PC view shows the menu items I have available on my desktop.  Hope this is a simple fix.  Thank you, ~ Peter Ferber
Windows program does not reveal "Preferences".
Free Tool: Path Explorer
LVL 12
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

>>> re.match("asd,asdasd,asd(\d)+","asd,asdasd,asd12312312").group(1)

I can't understand the result.
I think the result should be '1'
Hello, I am trying to get the formatting for my output (results) to match up with the header. I cant seem to get it to align irregardless of the values under the header.  Does anyone have a trick for this? Thanks in advance!
Desired output:
User Entry      Numbers Generated      Message                  Award
1, 2, 3            5,1, 3                          Two Matching      $100

import random
def lottery(x):
    set1=list(set(x)& set(win))
    if x==win:
        message='Three matching in exact order'
    elif x[0]and x[1]and x[2] in win==True:
        message='Three matching, not in order' 	
    elif len(set1)==2:
        message='Two matching' 	
    elif len(set1)==1:
        message='Any one matching'
    elif len(set1)==0:
        message='No matches'
    header='{:>0}{:>20}{:>12}{:>17}'.format('User Entry','Numbers Generated','Message','Award')

def labMenu():
    print('Enter 1 for Lottery')
    print('Enter 2 for Rock, Paper, Scissors')
    print('Enter 3 to exit the program')

done = False

while not done:
    choice = int(input('Please make an entry: '))

    if choice == 1:
        print('Guess three numbers between 0 and 9')
        guess1 = int(input('Enter first guess: '))
        guess2 = int(input('Enter second guess: '))

Open in new window

I'm doing my new network-game server in Java again, for a python client, btw,
I have this Java helper method below to convert the message bytes into an integer, that I'd like  to verify first.

What would it look like in Python? Is there a simple way to do it that I don't know about? I know that unexpected errors can occur with casting, for Python newbs
Are bit level operations the same operators?
Is getting the first byte simple in Python also?   just  (byte)  x

Java code to work inPython:
byte SecondByte(int x) {
		return (byte) ((x & 0x0000ff00) >> 8);

	static int intFromBytes(byte firstByte, byte secondByte) {
		if ((secondByte&0x80)==128) {
			//negative number
			return (int) ( (firstByte&0x000000ff)| ((secondByte&0x000000ff) << 8) | 0xffff0000 );
		} else {
			//Positive number
			return (int) ( (firstByte&0x000000ff)| ((secondByte&0x000000ff) << 8) );

Open in new window

All the best modern games are pseudo 3D, like League of legends and Starcraft 2.

Is it pseudo 3d? - It is 2D images used smartly at correct locations?

How do Starcraft 2 and League of Legends achieve their 3D feel?

Would Python be able to do decent game-play FPS & updates in time with my client networking class?
MIT and everyone is teaching CS100 in Python, and I've seen some promising 2D demos.
Hello! Having trouble with my python code. Two issues-
One- How can I format this nicely, so that the values of the dictionary line up under the header? I was able to get all the keys to print on separate lines but that's it.
Two- my loop that is supposed to give me the candidate with the most votes keeps pulling in the candidate with the highest key (the last input). Thanks in advance for any help!
Here is an example of the output I want
ID Name    Votes   %of Votes
1   Homer   90          90%
2   Dan        10         10%
and the winner is Dan!

dct = {}
i = 1
    name = input('Please enter a name: ')
    if name == '':

    votes = input('Please enter vote total for canidate: ')
    totalVotesInt= map(int, totalVotes)
    total = sum(totalVotesInt)
    dct[i] = list((name,int(votes)))   
    i += 1

maxVal = 0
for i in range(1, len(dct) + 1):
    if dct[i][1] > maxVal:
        maxInd = i
    dct[i].append(int((dct[i][len(dct[i]) - 1]) / total * 100))

header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print1=("\n".join("{}\t{}".format(key, value) for key, value in dct.items()))
print('Total '+str(total))
print('The Winner of the Election is '+ dct[maxInd][0])

Open in new window

The following GUI that is used to restore backups for a system.

import Tkinter as tk

root = tk.Tk()

v = tk.IntVar()
v.set(1)  # initializing the choice, i.e. Python

backups = [
    (200,"WIN_7", "active", 4096, 320, 1),
    (201,"WIN_7_sp1", "active", 4096, 320, 2),
    (210,"WIN_Java", "inactive", 8019, 8),
    (230,"Linux_C78", "active", 4096, 90),
    (241,"Linux2_B78", "active", 4096, 80)

def ShowChoice():

         text="""Choose a backup
to restore from the list:""",
         justify = tk.LEFT,
         padx = 20).pack()

for val, backup in enumerate(backups):
                  padx = 20,


Since the back up list is changing from one system to another, the script needs to be changed to list the available backups. If I run the program 'listbk', it outputs the list as follows:

ID      NAME           STATUS      MEM    Disk    RANDOMID
100     WIN_7          active      4096     320        1
301      WIN_7_sp1     active      4096     320        2
390      WIN_Java      inactive    8019     320        8
480      Linux_C78     active      4096     320       90
541      Linux2_B78    active      4096     500       80  

Inside the python script, I am able to run the script using the below …
I need a good book to learn Python.

My immediate goal is to be able to update Katoolin for Ubuntu 18.04 and maintain that software as I'm Cyber Security student. (You know I need to know Python if I'm Cyber Security).

I also want to create an open source version of the software, using either Python or Java. Would recommend thoughts on this and also recommend a good book for my goals.

I have this error occurred when installing Python2.7 on AIX 6 OS :

 error: command '/opt/freeware/lib/python2.7/config/ld_so_aix' failed with exit status 8

Can I install separately ld_so_aix ? How ? Where can I get the library ?

Thanks for your reply
How can one remove the header line in a file using Python?

Free Tool: IP Lookup
LVL 12
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.


If I put my keyboard listening in pygame in my drawing/game loop, it obviously won't be checked constantly.
I must obviously have a Thread listening for keyboard input, mouse movement to play my game and update internal game variables.

Is this just a new class I must make with two methods each to listen to pygame keyboard/mouse activity. Case closed?


Looking at League of Legends and the 3-D rendering it is capable of doing,
would a Python pygame program be able to do similar quality, w sound?


If Python can be run in a browser,

Will my RTS client's game window be playable? - how? - browser window? - in its own window?
It looks like printf's are written to the browser window, but will Threading occur normally?
I'll keep my invulnerable RTS server in Java. And do a client in pure Python now. Will it be as good as in Java?
I have the following regular expression:

Open in new window

It does a fine job of capturing the first parameter in a Python function declaration like this:
def GetStatus(Param1, Param2, Param3)

Open in new window

How do I alter the expression so that it can capture each argument? Bear in mind that this needs to work for any Python function declaration so it may have any number of arguments.

I'd like to convert my  Java RTS server client to python.

Do you think it will be a virtual mirror image, or might I expect some unforeseen issues?
Does Python underperform or mismatch in any areas?

Linux Centos, When I run a script  manually, it works perfectly but when I run it as a cronjob it throws an error from within the script. My script is a simple launcher for a Python script as follows:


cd /
cd /usr/local/bin
Python2.7 /root/amqp_to_db/ &
cd /

The error that I get is that "Python2.7 is not recognised as a command!


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.