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

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
JavaScript Best Practices
LVL 12
JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

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
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
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
I own a lot of servers, Virtual Private Servers in specific. Those resources are being wasted. How do I put them to good use to earn a substantial amount of money?
By the way, I didn't buy any of them. Just got them as a free credit.
Please give me detailed ideas and suggestions.

P.S.: I'm a techie. To be more specific, a Python Developer, and a Linux Systems Admin.
0
C++ 11 Fundamentals
LVL 12
C++ 11 Fundamentals

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

Hi, I'm running a python script using Spyder (Python 3.5) on OSX 10.13.6 and keep on running into file not found errors when attempting to copy data into a Microsoft Excel file. It looks like a permissions issue, but I don't know how to resolve. Any help would be much appreciated,

import urllib.request
import pandas as pd
import sys
import os

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

from html_table_parser import HTMLTableParser

target = 'weblink'

#get website config
req = urllib.request.Request(url=target)
f = urllib.request.urlopen(req)
xhtml = f.read().decode('utf-8')

#instantiate he parser and feed it
p = HTMLTableParser()
p.feed(xhtml)

#write the table into python list

cwd = os.getcwd()  # Get the current working directory (cwd)
print(cwd)

Table_List = p.tables

# Use the Pandas from_dict method to read the tables into
# a Pandas data frame

df = pd.DataFrame.from_dict(Table_List[0])

#CountryDied_Stats.to_excel('/Users/bhav\ 1/Documents/keepbak2/python/countrydiedtest.xlsx',
#                           na_rep='',
#                           float_format=None, columns=None,
#                           header=True, index=True,
#                           index_label=None, startrow=0,
#                           startcol=0, engine=None, merge_cells=True,
#                           encoding=None, inf_rep='inf', verbose=True)

#print(CountryDied_Stats)
#xlfile = 'countrydiedtest.xlsx'
xlfile = '/Users/bhav\ 

Open in new window

0
Dear Experts,

Actually having the following Python code to import .csv file and it works fine:

import csv

with open(r"C:\File.csv") as csvfile:
    rows = list(csv.reader(csvfile))
    data_header = rows[0]
    data_rows = rows[1:]
    

Open in new window


I would like to restructure a little bit with adding the path to a variable as FilePath and using that in the open command, around like this (it does not work of course in this format)

import csv

FilePath = "C:\File.csv"

with open(r % FilePath) as csvfile:
    rows = list(csv.reader(csvfile))
    data_header = rows[0]
    data_rows = rows[1:]
    

Open in new window


Could you please advice about the Python syntax including a variable like that?

Thanks in advance,
0
Dear Experts,

I have a small Excel file with the data as it the below print screen shows:
Excel file
which are imported by Python through a .csv file by the following code:
import csv

with open(r"C:\Users\ac324485\Downloads\Daily files\File.csv") as csvfile:
    rows = list(csv.reader(csvfile))
    data_header = rows[0]
    data_rows = rows[1:]
    
for x in data_header:
    print(x)
    
for x in data_rows:
    print(x)

Open in new window


Could you please advise which Python syntax could write back data to that Excel file to cell A2 (so to the place of value '10101')?

Thanks in advance,
0
Dear Experts,

I have a small Excel file with the data as it the below print screen shows:

Excel data
which are imported by Python through a .csv file by the following code:
import csv

with open(r"C:\Users\ac324485\Downloads\Daily files\File.csv") as csvfile:
    rows = list(csv.reader(csvfile))
    data_header = rows[0]
    data_rows = rows[1:]
    
for x in data_header:
    print(x)
    
for x in data_rows:
    print(x)

Open in new window


and which can be seen as result (the first row as header in data_header array, while the next of the rows as data line in data_rows array:

Imported .csv data
Could you please advise how to refer/get the value for '10101' in cell A2?

Thanks in advance,
0
Dear Experts,

Could you please advise in Python how to get all the attributes/methods of an object?

Actually I need to write a Python code which works together with SAP application and it took almost a week to find in separate Python codes through Google, that there are 'Info' and 'SystemName' attributes for the "SAPGui" object.

This code so works already with showing the system name of that connection in SysName variable:

import win32com.client

SapGui = win32com.client.GetObject("SAPGUI")
print(SapGui)
Appl = SapGui.GetScriptingEngine
print(Appl)
Connection = Appl.Children(0)
print(Connection)
Session = Connection.Children(0)
print(Session)
CollCon = SapGui.GetScriptingEngine.Children(0)
print(CollCon)

SysName = Connection.Children(0).Info.SystemName
print(SysName)

Open in new window


Now it can be even in one line:

FullAttr = win32com.client.GetObject("SAPGUI").GetScriptingEngine.Children(0).Children(0).Info.SystemName
print(FullAttr)

Open in new window


And here comes my question concretely - what is the way to find these attributes like Info and SystemName in Python for such outside application? I am using Spyder for writing Python code and the default tool which brings a list after pressing '.' for the object, it does not work for such outside application
Attribute finder in Spyder
Thanks in advance,
0
I've started a python script to scrape a table from a website and print to console, but I'm having trouble displaying the content in the table format as displayed on the website. I'd appreciate some help with the information formatting and getting information from individual cells to be used for calculations.

import os
import os.path
import requests
from bs4 import BeautifulSoup
url = 'https://www.hl.co.uk/shares/shares-search-results/a/aviva-plc-ordinary-25p/financial-statements-and-reports'
headers= {'User-Agent': 'Mozzilla/5.0'}
response = requests.get(url, headers = headers)
soup = BeautifulSoup(response.content, 'html.parser')
stat_table =soup.find_all('table', class_ ='factsheet-table responsive')
stat_table = stat_table[0]
len(stat_table)

for row in stat_table.find_all('tr'):
	for cell in row.find_all('td'):
		print(cell.text)

Open in new window

0
Dear Experts,

I need to transfer a VBA Excel code to Python, simply having the following variables and they work fine in VBA:

Set SapGui = GetObject("SAPGUI")
Set Appl = SapGui.GetScriptingEngine
Set Connection = Appl.Children(0)
Set session = Connection.Children(0)
Set CollCon = Appl.Connections()

Open in new window


Regarding Python it works fine also till this point:

import win32com.client

SapGui = win32com.client.GetObject("SAPGUI")
print(SapGui)
Appl = SapGui.GetScriptingEngine
print(Appl)
Connection = Appl.Children(0)
print(Connection)
session = Connection.Children(0)

Open in new window


but being not sure in which format the CollCon variable should be in Python?

I tried this syntax:

CollCon = SapGui.GetScriptingEngine.Children([])

Open in new window


but that brings the following error message:

com_error: (-2147352567, 'Exception occurred.', (618, 'saplogon', 'Bad index type for collection access.', None, 0, 0), None)

Thanks in advance,
0
Hi Experts,

   How to delete the existing elasticsearch cluster and how to create a new elasticsearch cluster?  Please throw some best practices.

With Many thanks,

Bharath AK
0
Hi:

 Trying to return all columns that contain the max of the same column, but seem to be running into an error:


import numpy as np

def answer_one():      
    return [df.where(df['Combined total']=numpy.max(df['Combined total']))]


  File "<ipython-input-8-ff62b3bbcead>", line 4
    return [df.where(df['Combined total']=numpy.max(df['Combined total']))]
                    ^
SyntaxError: keyword can't be an expression
0
Amazon Web Services
LVL 12
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

I'm trying to create a Tkinter tutorial https://likegeeks.com/python-gui-examples-tkinter-tutorial/amp/

I'm running Ubuntu 18.04 with Python 3.6.5 installed.

Here is my code

from tkinter import *

window = Tk()

window.title("Welcome to LikeGeeks app")

window.mainloop()

Open in new window


I get an error that Tk() is not defined.

When I run sudo apt install python3-tk it says it is already installed.

I have run variations of the code below

window = Tkinter()
window = tk()

Open in new window


All of these say they are undefined.
0
Dear experts,

I need to write a Linux shell script that can automate filesharing using Implicit SSL/TLS (Port 990).

Python can be useful as well for this...

This needs to be done using a Linux Mate desktop.

Bottom line I need something like this to work (I think): curl --cert us.pem --user usergiven:passworm --upload-file file.txt ftp://sftp.remoteserver.com:990

I am not able to find anything on the internet yet...

Thank you in advance
0
Help with python script,  enters an infinite loop. I was expecting to stop upon hitting it's limit.

import random
def rollDice():
	roll = random.randint(1,100)
	if roll == 100:
		print roll, 'roll was 100, you lose sucker, play again!'
		return False

	elif roll <= 50:
		print roll, 'roll was less 50, than you lose sucker, play again!'
		return False

	elif 100 > roll > 50:
		print roll, 'roll was greater 51 and less than 99, you win, jammy sod!'
		return True


def gamblers_cash(funds, initial_wager, wager_count):
	value = funds
	wager = initial_wager

	currentWager = 0

	while currentWager < wager_count:
		if rollDice():
			value += wager
		else:
			value -= wager

	currentWager += 1
	print 'Funds:', value

gamblers_cash(2000,100,100)

Open in new window

Screen-Shot-2018-08-15-at-23.18.50.png
0
Hi :

 In Jupytr notebook, I seem to be getting error on a simple import. Any idea why?

import pandas pd


File "<ipython-input-13-6bfc1f40d5ca>", line 1
    import pandas pd
                   ^
SyntaxError: invalid syntax
0
Sorry for the general question but I have researched on the internet and not found the definitive answer I was looking for and was looking for clarification.

I am looking to set a process on my web server (I am running Apache on Linux) to run each night to email a summary to a user of their data (based on some SQL query.

I just want to know the general approach that people would take to do this, in that...

  • how do you set processes to run at specific times or based on an event and;
  • which language is conducive to doing this in terms of running a process based on SQL and generating emails from it?
  • I am also looking at how to run a process that deletes data more than 10 years old (i.e., if the created date in the database was more than 10 years ago, run a process to delete that data each night - would this be the same approach?

Thanks in advance ofr the advice.
0
Dear Experts,

I have the following data in the table on the printscreen,
Example data
which are actually imported from a .csv file by this Python code and as you can see also started to setup a histogram chart with those plt. related lines:

import csv
import matplotlib.pyplot as plt

with open(r"C:\Demo.csv") as csvfile:
    rows = list(csv.reader(csvfile))
    data_header = rows[0]
    data_rows = rows[1:]

plt.ylabel("Points")
plt.xlabel("Weeks") 
plt.xticks(range(0,5))
plt.yticks(range(1,21))
plt.title('Demo chart')
plt.show()

Open in new window


My question would be actually, that instead of the line:

plt.xticks(range(0,5))

Open in new window


how to use the content of data_rows[0] so the header values from my table? (concretely so Week1, Week2, Week3, Week4). Would be that line something like plt.xticks(data_header[0])? (it does not work in that format)

Thanks in advance,
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.