Python

3K

Solutions

23

Articles & Videos

2K

Contributors

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 All,

I am new to python and coding overall. I am trying to make sense out of a particular line in the code below. This code will be used to see the files in my recycle bin. In  the second line, what are "curr, dirs, files"? are those fields, arguments of os.walk() function? I have noticed that if I change for instance "curr" for any other name, and change that parameter in the "path" line, the program still works. I am actually a little confused.

import os
rootrec = "C:\\$Recycle.Bin"
for curr, dirs, files in os.walk():
    for f in files:
        path = "%s/%s" % (curr,f)
        print(path)

Any clarification will be helpful!
0
Enroll in June's Course of the Month
LVL 8
Enroll in June's Course of the Month

June’s Course of the Month is now available! Experts Exchange’s Premium Members, Team Accounts, and Qualified Experts have access to a complimentary course each month as part of their membership—an extra way to sharpen your skills and increase training.

I am looking to replace the value between two spaces in a string with a backslash. Can someone assist with the syntax.

E.G. I want

RED 123456789 White

to become

RED\White

Thanks
0
Hello all,

I am new to Python and I have a couple of questions regarding the code below. I am currently going through a lesson that shows you how to replay packets using scapy. In my try block on the code below, what does "frame[Ether].src" and "frame[IP].src" where did I get these variables from?
Is ".src" a module? what is "[Ether]" and [IP]?

I hope you guys can clarify.

Thank you!

from scapy.all import *
from scapy.utils import rdpcap

src_mac = "08:00:27:ae:6f:d7"
dst_mac = "08:00:27:87:57:be"
src_ip = "192.168.1.118"
dst_ip = "192.168.1.117"

frames = rdpcap("/root/pcaps/ping_traffic.pcap")
for frame in frames:
    try:
        frame[Ether].src = src_mac
        frame[Ether].dst = dst_mac

        if IP in frame:
            frame[IP].src = src_ip
            frame[IP].dst = dst_ip

        sendp(frame)
    except Exception as e:
        print(e)
0
I have a python script that will construct a list of futures contracts for a specified symbol, exchange, and year window.  The script will download pricing information from Quandl for each contract in the strip.  This script works properly.

import pandas as pd
from pandas import ExcelWriter
import quandl

symbol = 'ES'
exchange = 'CME/'

start_year = 2015
end_year = 2016


#Constructs a list of futures contract codes for a particular symbol
#and timeframe.
futures = []
months = 'HMUZ'
for y in range(start_year, end_year+1):
    for m in months:
        futures.append("%s%s%s%s" % (exchange, symbol, m, y))

#Download the data from Quandl.
for f in futures:
    quandl.ApiConfig.api_key = "xxxx"  
    data = quandl.get(str(f))
    data = data.drop(data.columns[[3, 4, 7]], axis=1)

I have another python script that will create a continuous futures contract from 2 consecutive contracts in the futures strip.  It uses the perpetual method; identifying the roll date as the first day where volume of the far contract exceeds volume of near contract, and then adjusts the prices of the previous 4 sessions to roll date by weighting the near and far contracts in increments/decrements of 20%.  This script works properly.

import pandas as pd
from pandas import ExcelWriter
import quandl

#Get quandl futures data
quandl.ApiConfig.api_key = "xxxx"    
contract_near = quandl.get("CME/ESH2015")
contract_far = quandl.get("CME/ESM2015")

#Drop the columns …
0
I have a list (named bob) and I want to reverse the order of the list without reversing the whole list.  So, for example my bob list would be [Bob, Mom, Dad, Kelsey] and I want to reverse it to read [boB, moM, daD, yesleK] instead of [yesleK, daD, moM, boB].  

I know I have to iterate through each line and add the extracted line in from of the accumulating string, but I’m not sure how to set up the FOR loop to do so.  How would I do that?
0
I had this question after viewing linux crontab output.

Hi everyone,
right now I am manually running this script to start a python app. I would like to do this @ reboot.

cd /home/ec2-user/console

python console.py 8090 cloud& <<this runs fine

I tried to create a small bash script ,but cant seem to make it run @ reboot time

#!/bin/bash
cd /home/ec2-user/console
python console.py 8090 cloud&

crontab -e

@reboot sh $HOME/boot_python.sh <<dosnt work

the script runs when executed manually but not @ reboot

Peter
0
There are x students and y tents placed randomly on a field of dimensions 1000 by 1000 (including(0,0,)). A tent can only house up to 10 students. As a curfew is in place, all students have to find a place in the tents. I have to assign students to tents such that the number of steps walked by the students will be miNimized. Students can only move horizontally and vertically, so if their location is (0,0) and the tent's location is (10,10) then they must walk 20 steps to reach the tent.
The location of the tents will be stored in a file called tents.csv, and the location of the students stored in a file called students.csv.  
The program should read the locations of each and output the results in a file named output.csv where:
- the first row contains the number of total steps walked
- from the second row, each row contains [student ID, tent ID, steps walked, student x location, student y location, tent x location, tent y location]

The program should be able to execute any range of values as defined in the problem definition.


P/s: anyone who know how to solve please please please help me...this is the project that can decide my future......ㅠㅠㅠ
0
This code does 3 things:
1. Gets a list of ticker symbols
2. Gets pricing information from Google finance
3. Inserts the pricing information into a MySQL table

The code runs without returning any errors.  However, the MySQL table is not populated with the information.  The following is returned:
Empty DataFrame
Columns: [open_price high_price, low_price, close_price]
Index: []

I can't figure out why. Advice is needed and appreciated, thank you.

# price_retrieval.py

import datetime as dt
import MySQLdb as mdb
import pandas_datareader.data as web

# Obtain a database connection to the MySQL instance
db_host = 'localhost'
db_user = 'xxx'
db_pass = 'xxxxx'
db_name = 'securities_master'
conn = mdb.connect(db_host, db_user, db_pass, db_name)

#Obtains a list of the ticker symbols in the database.
cur = conn.cursor()
cur.execute("SELECT id, ticker FROM symbol")
data = cur.fetchmany(10)    

#Get daily historic data from google
start_date = dt.datetime(2005, 2, 1)
end_date = dt.datetime(2005, 2, 28)          
for d in data:
    try:
        gf_data = web.DataReader(str(d[1]), "google", start_date, end_date)
    except:
        pass
   
    # Create the time now
    now = dt.datetime.utcnow()
   
    #Create dictionary for db
    pricing_info = {
        'symbol_id': d[1],
        'price_date': now,
        'created_date': now,
        'last_updated_date': now,
        'open_price': gf_data['Open'],
        'high_price': …
0
How to save the output of show run (Router) in text file on desktop using python.
I have a router i have to save its config file in desktop in text format using python
0
Im trying to save the output of show run to my desktop but its not getting executed.. pls help

import paramiko

client=paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
com="ls ~/desktop"
client.connect('192.168.1.12', username='cisco', password='cisco')
output=""
stdin, stdout, stderr = client.exec_command('show run')

print "ssh succuessful. Closing connection"
stdout=stdout.readlines()
client.close()
print "Connection closed"

print stdout
print com
for line in stdout:
    output=output+line
if output!="":
    print output
else:
    print "There was no output for this command"

Open in new window

0
Announcing the Most Valuable Experts of 2016
LVL 6
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

I'm in the Business Intelligence Department, but practically speaking we're the Reporting Department, your basic operational type of reports - lists, lists, and more lists.

I'm at an institution of higher learning, and a new project has come up for the Math Department. They want to know relationships between courses, grades, etc.

Examples:

- if someone gets a D in Calc I, what's the likelihood of graduation?  with various permutations, like taking Calc I again
- what's the likelihood of someone getting a D in Calc I, getting a D or F in Calc II
- for placing incoming students in Pre-Calc or Calc I, what are the factors that indicate success? such as Verbal SAT

So I think I've targeted the right discipline (Analytics), but not sure where to take this project.
0
Is there a way to export/extract all the values/items from a drop-down field in a PDF?

I have a PDF form, and it contains a few drop-down boxes that I can select.  I want to be able to export/extract all the values contained inside this drop-down.  Is that possible?
0
Hello, Experts,

Running into an issue with my python script erroring out when grabbing input from end-user and passing it to the SQL update command then executing.

Can you help me figure out what is wrong?

CODE:
def option_two():
    getCIM = int(input('Enter a store CIM number you want to edit:'))
    print('')
    print('You entered %s' % getCIM)
    print('')
    getstore_UIN = input('Enter the UIN you want to update for the the CIM you entered:')
    print('')
    print('You have successfully updated the store information database for')
    #create connection ODBC driver
    cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER={test};DATABASE={ROWStage};UID={test};PWD={test123}')

    cursor = cnxn.cursor()

    #variables that grab user input variables and passes them to SQL command
    store_UIN = getstore_UIN
    store_CIM = getCIM

    SQLCommand = ("UPDATE StoreInfo SET store_UIN = ? WHERE store_CIM = ?", store_UIN, store_CIM)
    #store_UIN, store_Num, store_FileName, store_Name, store_CIM, store_OpeningDate, store_Email, store_Bays, store_Operator, 
    #store_Phone, store_Market, franchisee_Email, store_Street, store_City, store_State, store_Zip
    #("UPDATE progress SET CockpitDrill = ? WHERE progress_primarykey = ?", newcockpitdrillvalue, oldprimarykeyvalue)

    #stores getcim variable into a readable variable list
    cursor.execute(SQLCommand, [store_UIN])
     
    #commit the sql command
    cnxn.commit()

    input('Press enter to exit program')

Open in new window


ERROR:

error.jpg
0
I run an order import routine and I am modify a python script to check that they are in the system once it is done importing.  My code lookeds like this.  I am trying to learn the pieces of putting this together.  If I take the date part out I can get it to return orders to the screen so I know it is a formatting issue on the date that is making this not work correctly. I am using the pyodbc library.

d = datetime.datetime(2017, 5, 3)
print (d)
sql = "select OrderNum, POnum, OrderDate from PUB.OrderHed where OrderDate ="+d
cnxn = pyodbc.connect("DRIVER={Progress OpenEdge 10.1b Driver};HostName="+host+";DATABASENAME="+database+";PORTNUMBER="+port+";LogonID="+login+";PASSWORD="+password)
cursor = cnxn.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
for row in rows:
    print(row.OrderNum, row.PONum, row.OrderDate)

this is what it returns.

    sql = "select OrderNum, POnum, OrderDate from PUB.OrderHed where OrderDate ="+d

TypeError: must be str, not datetime.datetime

I have tried everything I can find to convert to a string but then I am not sure that if it is a string format trying to pull a datetime format from progress if that is the error.

Any help would be greatly apppreciated.
0
I have an ssh client called "termius" to import all my hosts from a notepad. I am using a script with python and github to make all this work. I dont know much about scripting at all but I've been provided with all these tools to make this work. Does anyone know what the error below mean? As you can see the import was successful but it errors out later. I'm using a siple notepad file. I provided a snip it of how it looks.

notepad:
Abilene North Place,10.50.72.254
Abilene South Place,10.50.65.254
Abilene west Place,10.50.65.251
Addison Place,10.50.27.254
test 500,5.5.5.5

a.png
0
I have used Python, Natural Language Processing and web scraping technology to do some deep mining of Google's vast warehouses of articles on the web.

Is what I described considered artificial intelligence?

Or, in order to satisfy the requirement of AI must that model also automatically adjust it's algorithms based on the results of the searches? In my case, the adjustments were manual.

Curious.

Thanks.
1
I have a python script i need to run in a windows scheduled task to pull data from an API.  

The output of that script needs to be appended to an output file in a specific directory.

Anyone got good experience with this?

Thanks in advance
0
Dear all,

I am creating a chart in a Jupyter Notebook.  The chart is created, although its not a box plot and no color.  See attached (I have cropped the axis from the image).

import matplotlib.pyplot as plt 
import seaborn as sns
plt.figure(figsize=(14,6))
my_palette = sns.color_palette("muted")
sns.boxplot(x="Company", y="Value", data=data, palette=my_palette)

Open in new window


Thanks
chart.png
0
Dear all,

How to convert the below line of code to add the mean, min, max as columns to the df.

I'm not able to plot these values, as they are not recognised for the axis.

df = data.groupby(['GlobalArea','', 'Company'])['Values'].agg(['mean', 'min', 'max'])

Open in new window


Thanks
0
Free Tool: SSL Checker
LVL 8
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

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.

is there a macro that would delete row 2 in every file in a windows folder? these are CSV files - so i suppose i will need to convert them all to excel as well.
0
i want use this command on my Python script :

 killall tor  && service tor start 

Open in new window

  How can i do it on Python ?
0
HI all,
I'm trying to check the value generated doesn't already exist as dict value.  If it exists a new value is required and it must be validated against the conditions in the while statement.  The below code block isn't working the same generated value exists for multiple keys. I can't change the GetResult method.

                if isNaN(row) == False:
                    value = GetResult(type)
                    while (value == row or value in dict.values()==True):  
                        value = GetResult(type)
                    dict.update({(row):(value)})

Open in new window


Thanks
0
I am using the visual debugger in PythonWin on a Windows 7 platform with Python 2.7.  I am not using pdb.  I'm trying to debug code written by someone else.  I have set some breakpoints and am stepping through the code.  There are some for-loop variables in the code.  As I go through the code I would like to see the changes to these values.  However, they don't seem to change.  If I execute a print in the Interactive Window I see the correct value.  But all I see in the list of values in the visual debugger is the initial value.

Is there something I need to do to get the variables to refresh every time they are updated?

Any help would be much appreciated.  There is not a lot of documentation on the PythonWin visual debugger which is easier/quicker to use than pdb ... if I knew how to use it!  ;-)

Thanks.
0
I need to set up the question ask user what type of the device they use and ask them question them print out the solution!
e.g. : computer: What type of OS you use?
          users: IOS
          computer: is your screen working?
          users:.........
Then I write that program but it don't work, can someone help please?
s1 = ('if you drop it into the water then try to put it into the rice, if not please replace the screen! ')
s2 = ('please go to the local shop to check your phone!')
s3 = ('please repleace the button!')
s4 = ('please turn on the power!')
s5 = ('Please try with different charge')
s6 = ('please charge your phone fully')
s7 = ('please replace your batter')
s8 = ('please delete some app for your phone to install a new app')
s9 = ('please turn up the volume')
s10 = ('please replease the speaker frome your phone!')
s11 = ('That good! If you have other any problem please go to our shop and check with the staff')
def android():
problem1=None
while problem1 not in ('yes', 'no'):
     problem1=input("Is your screen working?")

if problem1=='no':
    problem2=None
    while problem2 not in ('yes', 'no'):
        problem2=input('have you drop your phone or have you drop it into the water?')

    if problem2=='yes':
        print(s1)
    elif problem2=='no':
        print(s2)

elif problem1=='yes':
    problem3=None
    while problem3 not in ('yes', 'no'):
        problem3=input('is the button working?')

    if problem3=='no':
        print(s3)
    elif 

Open in new window

0
Hi All,

I have decent powershell skills, I now want to learn either Ruby or Python , which language will you recommend  and which will be the easiest for someone from a powershell background?

Also do any know if if chef configuration management support python?

thank you in advance
0

Python

3K

Solutions

23

Articles & Videos

2K

Contributors

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.