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 have a python program -- and I am a terrible programmer -- that works but it is very slow because it takes a network address from a file and tries to find an address within that network from another file, so for each line in file A it reads through file B for every line in file A. There has to be a more efficient way to do this but I can't figure it out.

the vlans file looks like:
vlan10 testvlan 10.1.1.0/24
vlan11 devvlan 10.2.1.0/24

the hosts file looks like:
bob 10.1.1.3
ted 10.1.1.4
tom 10.2.1.4
tim 10.2.1.7

and the output needs to look like:
 
vlan10 testvlan 10.1.1.0/24 bob 10.1.1.3
vlan10 testvlan 10.1.1.0/24 ted 10.1.1.4
vlan11 devvlan 10.2.1.0/24 tom 10.2.1.4
vlan11 devvlan 10.2.1.0/24 tim 10.2.1.7

I need to read through the host file and find the ip address corresponding to the network in the vlan file.

In reality, the vlan file contains about 3000 vlans, and the host file contains 50,000 hosts.

This code works, but it is terribly inefficient. Also, I realized going back and forth between python2 (my linux box) and python3 (my windows box) there are issues with "unicode".

I would really appreciate some help.

Thanks,
Steve




#!/usr/bin/python 
import ipaddress

vlan = "/home/steve/vlp/vlans"
host = "/home/steve/vlp/hosts"

with open(vlan, "r") as vIN:
	for index, line in enumerate(vIN):
		var = line.split(' ')
		global net
		global netu
		net = unicode(var[2]).strip("\n")
		netu = ipaddress.ip_network(net)
#		

Open in new window

0
OWASP Proactive Controls
LVL 12
OWASP Proactive Controls

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

Hello Experts,

Can someone let me know where I can find practice questions on Python and SQL please? Particularly for beginners

Thanks
0
How can I use Python specifically tkinter to create a GUI to show a register of data from an MS Access table?

Thanks!
0
Hello Experts,

I'm not sure if there are many Databricks experts on this site, but I'll ask anyway.

I have written the following code in Databricks

dbutils.widgets.text("name", "Please Enter Your Name: ")
dbutils.widgets.text("age", "How old are you? ")
dbutils.widgets.text("guess", "Guess a Number")

name = dbutils.widgets.get("name")
age = int(dbutils.widgets.get("age"))
guess = int(dbutils.widgets.get("guess"))

print("Please guess a number between 1 and 10: ")
if guess < 5:
  print("Please guess higher")
  if guess == 5:
    print("Well Done, matey, you guessed it!")
  else:
    print("Bad luck you guessed incorrectly")

Open in new window


However, when I input 5 the number 5 the answer I get back is:

Please guess a number between 1 and 10:

However, I should get back the answer:

Well Done, matey, you guessed it

Can someone help figure out why
0
Have 2 ubuntu installations on Oracle VM. They are in the same version. I ran the same python script against its own ubuntu in the exactly same way. Ran well on one, but got the error on the other one below:
"ModuleNotFoundError: No module named 'x'".
I knew the one without error was installed more packages, but I did not remember which more packages were installed. Under this condition, how to troubleshoot this issue? Can any gurus shed some light to it? Thanks a lot.
Background:
ubuntu 18.04 on VirtualBox V5.2.22 in Windows 7 (2 Ubuntus installed on the same box).
0
Running Windows 7 pro on an HP z230 computer.
I just installed Visual Studio Community edition.    I selected the option to install support for Python.  Two of the selections offered were to install Python v3.7 or Anconda 5.3.
I am a bit confused .   According to the www.anaconda.com website, it seems the most recent Anaconda version is 2018.12.

Q1.) What is the latest version of Anaconda?
Q2.) What is the best way to install Anaconda and use it with Visual Studio?
Q2.) What happens if I install Anaconda without installing Python v3.7 first?
0
Hello All,
when running the below python script from the terminal to change an interface MAC, I get the following message: "siocsifhwaddr cannot assign requested address"

any ideas of what could be happening?

---------------------------------------------------------------------------------------------------------------------------------
#!/usr/bin/env python

import subprocess

interface = "eth0"
new_mac = "11:22:33:44:55:11"
print("[+] Changing MAC for " + interface + " to " + new_mac)

subprocess.call("ifconfig " + interface + " down", shell=True)
subprocess.call("ifconfig " + interface + " hw ether " + new_mac, shell=True)
subprocess.call("ifconfig " + interface + " up", shell=True)

-----------------------------------------------------------------------------------------------------------------------------------------
0
I need to read through 1000's of config files and get a list of all VLANs, their description and their IP address and mask. The data looks like:

interface Vlan100
  description Just a vlan
  no shutdown
  no ip redirects
  ip address 1.1.1.1/26

interface Vlan200
  description Just aother vlan
  no shutdown
  no ip redirects
  ip address 2.2.2.2/26

And there lots of other configuration data in the config file that I don't care about. What I have right now is a python program that opens the config file, and reads through looking for 3 strings: "interface Vlan", "  description", and "ip address". The problem, if you know Cisco, is that 2 of those strings occur in places other than vlan definitions.

I am trying to work through the logic of:

Find the line that contains "interface Vlan"
Write that line
and read the lines looking for "description" and "ip address" UNTIL I find another line that says "interface Vlan"

Make sense? I can run the python script now and then delete all the lines up until the first VLAN line and then delete all the lines afterword. But that will be very time consuming for all the files I have to work with.

Thanks in advance for your help.

Steve
0
Hi ..
I have template file as shown below:
locations total
building1 89.89
building2 678.45
building3 789.56
building4 45.90

Open in new window

I have python script that needs to read the template file and set values for the variables as shown below:

place1= is always the value on the second row of first column
number1 =  is always the value on the second row of second column
place2= is always the value on the 3rd row of first column
number2 =  is always the value on the 3rd row of second column
place3= is always the value on the 4rd row of first column
number3 =  is always the value on the 4rd row of second column
place4= is always the value on the 5rd row of first column
number4 =  is always the value on the 5rd row of second column

Open in new window


How can I read the file and set the variables in python.

Thanks.
0
Hi..
in a python script how can i get all the ip address of  the DNS servers on the network.

Thank you for your help.
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.

Dear Experts,

I would need to create a .bat file under Windows, which is able to:

1) run a .py so Python file and
2) also containing credentials as the Python code needs to connect to SQL and download data.

Could you please advise about the syntax how such .bat file should look like concretely?

Actually having the following try but it does not work (it executes the Python code but not asking for the password for the user):

@echo off
runas /netonly /user:smea\csehz
"C:\Python27\python.exe" "C:\Users\csehz\Desktop\HelloWorld.py"
pause

Open in new window


Thanks in advance,
0
Hi,
Trying to convert a python script into executable one file using pyinstaller in Linux. In my python script using subprocess I call few bash files, what is the best way to add them to the
executable as well. I use the comamnd: "pyinstaller --one-file pythonscript" to build the executable.

Thank you for your quick prompts.
0
Hi ...

Trying running a python script that calls a bash script as sudo.  to get all the standard input/output using the below:
sas_cmd = ['sudo', 'apacheart']
proc = subprocess.Popen(sas_cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

Open in new window

it is not calling the script at all ....
But, if i do the following:
proc = subprocess.Popen(['sudo','/usr/bin/apacheart'])

Open in new window

It calls the script.
Can someone please help to get the std/stout.
Thanks
0
Hi,

I am using the following Python code in a bigger script, but when some excel files (.xls) are corrupt I get the following error:

raise XLRDError('Unsupported format, or corrupt file: ' + msg)

XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'X\xcf\x13\xe0\xa1\xb9\x1a\xe1'


It fails when opening a workbook that is corrupt (wb = xlrd.open_workbook(filepath)), which ends the script. Is there a way I can modify the script to bypass the corrupt excel file or move it somewhere else and allow the script to move on?


import pandas as pd
import os
import xlrd
import shutil
from os import path

for subdir, dirs, files in os.walk(r'C:\Temp'):
    for file in files:
        filepath = subdir + os.sep + file
        
        
        wb = xlrd.open_workbook(filepath)

Open in new window

0
Hi

As well as I open PHP scripts on my browser without to have PHP installed in my computer I want to open scripts written in Pyton in my browser (from my hosting page not localhost) without installing one in my computer. It is possible?

The file extension works with '.py" in my browser?

Thank you in advance
0
I would like to know if it's possible to retrieve an hashed password from ADAM with Python?

I've seen that DSInternals could allow that, but wouldn't work with ADAM.  Plus we don't need the password in clear text, just the hashed version.

(Using Windows Server 2012 R2, ADAM, Python 3.7)

Thanks
0
Here is a quick entry class problem in python. Please take a look.
When a car is rented out, I thought it only delete the item in the self.availableCars,
Why the item was also deleted in the self.OriginalInventory?

for example, we first rent a "Sedan" out and return it back, the price of "Sedan" is shown as $None after we return it.

please help.

Thanks,
RDB



class carRental:
    def __init__(self, listOfCars):
        self.OriginalInventory = listOfCars #make a copy of Original Inventory, so we can look up price when a car is returned.
        self.availableCars = listOfCars

    def displayCars(self):
        print()
        print("Here is a list of available cars for rent")
        print("**************************")
        for car in self.availableCars.keys():
            print("{}:${} per day".format(car,self.availableCars.get(car)))
        print("**************************")
        print()

    def rentOut(self, requestedCar):
        if requestedCar in self.availableCars.keys():
            print("You have requested {}, it is available. It will cost you ${} per day".format(requestedCar, self.availableCars.get(requestedCar)))
            print()
            del self.availableCars[requestedCar]

            print("here is the list of available cars")
            for car in self.availableCars.keys():
                print("{}:${} per day".format(car,self.availableCars.get(car)))

            print("here is the list of car in the original 

Open in new window

0
I would like to know of it's possible to get notified by Active Directory when a user has been added/removed from a group?

Is there a way in python to "subscribe" to have our program notified when this kind of event occur?

The only way i could detect those changes is to pool data periodically to see group changes.

(running python 3.7 on windows server 2012 r2)

yet, i've found pyad and python-ldap modules, but none of them seems to have functions for that.

Note: If it's not possible to be advised, then is there a way to just check with a single call "Is there any changes?"... and if there's some changes, i could browse a complete group to see these changes.

Thanks
0
hi Apple folks

i prefer using Xcode for Python programming but i notice it has no native support (or full-featured) for debugging Python using Xcode. or, probably i missed something with Xcode?

basically, how can i have full-featured debug functions for Python code using Xcode?

thanks,
bbao
0
Build an E-Commerce Site with Angular 5
LVL 12
Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

Using:
  • Microsoft Visual Code 1.28.2 x64
  • Python 3.7

I've the smallest code ever
import ldap
print (ldap.__version__)

Open in new window


And i'm getting the error:
  • Exception has occured: ModuleNotFoundError
  • "No module named 'ldap'

I've installed the Wheel found on Christoph Gohlke web site.
using this command: pip install .\python_ldap-3.1.0-cp37-cp37m-win32.whl

I've checked the dependencies as shown here:
Capture.PNG
What am i missing?

Because when i run the following command in terminal, i'm getting "3.1.0" which mean that it can find the ldap module.
python -c "import ldap;print (ldap.__version__)"

Thanks a lot for your help
0
I need a script written to take a large xml file and extract information into a csv or directly to an MS SQL Database.  Preferably in powershell.

Attached is the a 'sample' of the XML file.  The actual file size is ~800 mb.  I have a Python script that plods through it on smaller file sizes (~14mb), but will take an amazing amount of time for the large file.  Really even a script to preprocess the file and take out all the line items with ServicePointChannelID with the 400 range would be nice, then my python script would work good.

Attached is a sample xml file, a sample output file, and the python script that creates it.

Ideally it would be nice to go over to powershell with this from Python.
test2.xml
dataexport.csv
dataexport.py
0
Hi,
I'm trying to create a pandas DataFrame from some json, which has a series of arrays. I've tried the code below, but I get an empty DataFrame.
The expected output is:

id               name
_________________
2546558   A1
2156478   A2
3654785   A3
1236489   A4
7896324   B1
1597532   B2
9512347   B3
7536972   B4

import pandas as pd
import json

data = [  
   [  
      {  
         'id':2546558,
         'name':'A1',
      },
      {  
         'id':2156478,
         'name':'A2',
      },
      {  
         'id':3654785,
         'name':'A3',
      },
      {  
         'id':1236489,
         'name':'A4',
      }
   ]
    ,
   [  
      {  
         'id':7896324,
         'name':'B1',
      },
      {  
         'id':1597532,
         'name':'B2',
      },
      {  
         'id':9512347,
         'name':'B3',
      },
      {  
         'id':7536972,
         'name':'B4',
      }
   ]
]
   
val = json.loads(json.dumps(data))

val = pd.DataFrame(val)

def getreadings(dict):
    d = pd.DataFrame()
    d['id'] = dict['id']
    d['name'] = dict['name']
    return d

df = pd.DataFrame()
for i in range(len(val)):
    df1 = getreadings(val.iloc[i,1])
    df = df.append(df1)
    
print(df)

Open in new window

0
Hi
We talked a little about my approach to teaching neighborhood kids and adults, even, how to code.
I think we decided against going all out on Python right away. Do you still agree? I'd like to hold off on Python for a pure newbie.
K-12 focuses on Java, so I think Java for them is obvious.
I also think so, because polymorphism and class design will be important for making tablet, phone apps, as they are seriously non-novice projects. - Java will make 4 an easy transition
I'm going to start them off on Java and when they are blatantly ready, switch to Python, or their preferred device.
I could do Java and Python side-by-side?
Any suggestions?
Thanks
I'll start early next year

My padowan coders will excel
0
My computer operating system is Windows 7 pro .  

I am trying unsuccessfully to find code in Github.  I need help using the search feature.  Yes, I have searched Experts-Exchange first before posting this message.  I guess I just don’t know what key words to enter.

I have to write a program to switch last name, first name to first name, last name.  I am not a coding expert.  I was hoping to find some vbscript code which would perform the task.  I have to deal with all kinds of names.  In the data I have to convert  there are names with 3 elements like:

Joe Jones Hopkins

Then there are people who have just one name.  
And there are people with suffixes like Jr and III .  Example Joe Jones jr.  etc.

Please explain in detail how you would use Github search to find suitable code to do the above.  I would prefer vbscript but Python code would be suitable also.

Or may be there is an Experts-Exchange article which would help.

Thank you for your help.
0
i would look like ro analyse/describe data that is big over 300,000,000 rows do you python can be able to help me do this. how efficiently can i do thos
1

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.