Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Cingulate
Oct 23, 2012

by Fluffdaddy

dougdrums posted:

Python code:
noisymodule.print = lambda x : None
Haha take that noisy module!
Crank it up a notch.

Python code:
noisymodule.print = lambda x : del random.choice(noisymodule.keys())

noisymodule.warn = lambda x : os.remove(glob.glob(noisymodule.__file__.replace("__init__.py", "*"))

Adbot
ADBOT LOVES YOU

Eela6
May 25, 2007
Shredded Hen

Cingulate posted:

Crank it up a notch.

Python code:
noisymodule.print = lambda x : del random.choice(noisymodule.keys())

noisymodule.warn = lambda x : os.remove(glob.glob(noisymodule.__file__.replace("__init__.py", "*"))

Mods?

Cingulate
Oct 23, 2012

by Fluffdaddy
Somebody fix the code and put it on pypi pls

Gene Hackman Fan
Dec 27, 2002

by Jeffrey of YOSPOS
It has taken me far longer than i would admit to figuring out how to make a simple calculator-type program in python and tkinter.

In my defense, my familiarity with python roughly six months ago was knowing that it was a programming language, but that was about it. So I've been learning everything from scratch, never mind that I learn best from screwing up, backing up, and trying again.

The plan is for me to build onto that calculator program and link everything up with PySerial and PyParallel in order to control the scoreboards and lights for a game show set. By the time I've traced ports, rewired the busted stuff, and hammered everything down to work as I've intended, it should be roughly five years after the heat death of the universe.

But I will say that as much as I grouse over my own lack of skills, I am proud of what I've managed to accomplish so far.

huhu
Feb 24, 2006
In Pycharm, is there a way to run code and then and then leave some sort of a command line to continue playing around with it?

Thermopyle posted:

What?

PyCharm is amazing for HTML/CSS/JS. It's basically a superset of Webstorm which is already widely liked for webdev stuff. I often use PyCharm for projects that are only HTML/CSS/JS.

Maybe ask about some specific things you're missing and I bet you'll find that most of them are supported.

VisualStudio feels like the Photoshop of web development -- way too bloated. I realized that all the features I expected from PyCharm exist only in the professional version so now I've got myself a copy of that.

Proteus Jones
Feb 28, 2013



huhu posted:

In Pycharm, is there a way to run code and then and then leave some sort of a command line to continue playing around with it?

It's got a full featured debugger if that's what you're asking. Also has an integrated terminal and python console.

vikingstrike
Sep 23, 2007

whats happening, captain

huhu posted:

In Pycharm, is there a way to run code and then and then leave some sort of a command line to continue playing around with it?


VisualStudio feels like the Photoshop of web development -- way too bloated. I realized that all the features I expected from PyCharm exist only in the professional version so now I've got myself a copy of that.

Highlight code, right click, execute selection in console.

huhu
Feb 24, 2006

flosofl posted:

It's got a full featured debugger if that's what you're asking. Also has an integrated terminal and python console.

I guess to rephrase my question... In Python IDLE, I can run test.py, and then play around with it after.

test.py
code:
x = 5
code:
Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
>>> x
5
>>> x+5
10
>>>
Is this possible in PycHarm?

Proteus Jones
Feb 28, 2013



Yes

Grab the community edition and give it a spin.

huhu
Feb 24, 2006
I've been using PyCharm for awhile now I'm just not sure how to phrase my question in Google so I'm asking here.

vikingstrike posted:

Highlight code, right click, execute selection in console.

I highlight the entire file and do this and it gives errors.

Edit: Found it
http://stackoverflow.com/questions/21516027/running-code-in-pycharms-console

huhu fucked around with this message at 21:53 on Apr 27, 2017

Proteus Jones
Feb 28, 2013



huhu posted:

I've been using PyCharm for awhile now I'm just not sure how to phrase my question in Google so I'm asking here.


I highlight the entire file and do this and it gives errors.

Edit: Found it
http://stackoverflow.com/questions/21516027/running-code-in-pycharms-console

Huh.

I just tested it using the copy and paste method and it works fine. But if that method works for you.

code:
<a bunch of pasted code>

>>>print (validation_file_name)
1- Validation 04.27.2017 04.24 PM.csv

Jose Cuervo
Aug 25, 2004
I have read a large amount of data into a Pandas DataFrame from multiple .csv files (where each .csv file contained the same data but for different years). There are columns corresponding to test scores in the DataFrame which should all be numbers, however based on a df[col_name].unique() call it is clear that some files stored the numbers in the columns as numbers, some as strings, and sometimes when there wasn't a test score text was used ('No Score').

Because of this, I cannot use the .astype() functionality to convert the column to floats. What would be a good way to go about identifying the entries that are stored as strings and converting them to floats while at the same time identifying the entries that are text and replacing those entries with nan?

vikingstrike
Sep 23, 2007

whats happening, captain
Take a look at pd.to_numeric()

B B
Dec 1, 2005

I'm just getting into socket programming in Python and clearly have no idea what I am doing. I'm trying to write a simple TCP server that a client can connect to persistently and send phrases, which will be echoed back to the client in all caps.

Here's the contents of my server.py file:

code:
from socket import *

host = 'localhost'
port = 12007

server_socket = socket(AF_INET, SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(1)
print 'Server up'

while True:
    connection, address = server_socket.accept()
    sentence = connection.recv(1024)
    capitalized_sentence = sentence.upper()
    connection.send(capitalized_sentence)
Here's the contents of my client.py file:

code:
from socket import *

host = 'localhost'
port = 12007

client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect((host, port))

while True:
    sentence = raw_input('sentence: ')
    client_socket.sendall(sentence)
    modified_sentence = client_socket.recv(1024)
    print 'reply:', modified_sentence
The first message that I send is getting through just fine, and the server is responding with the capitalized sentence. When I attempt to send a second sentence, though, nothing happens. Can someone point me in the right direction?

ynohtna
Feb 16, 2007

backwoods compatible
Illegal Hen
Your while loop in server.py has server_socket.accept() within it, so it expects a new client connection to be made before receiving each sentence.

Meanwhile, client.py only connects to the server once before attempting to send multiple sentences (client_socket.connect(...) coming before the while loop in client.py).

Moving server_socket.accept() out of the while loop in server.py should get this basically working, but will mean that your server as it stands only supports a single client. But that's a problem that can be addressed later. :)

B B
Dec 1, 2005

ynohtna posted:

Your while loop in server.py has server_socket.accept() within it, so it expects a new client connection to be made before receiving each sentence.

Meanwhile, client.py only connects to the server once before attempting to send multiple sentences (client_socket.connect(...) coming before the while loop in client.py).

Moving server_socket.accept() out of the while loop in server.py should get this basically working, but will mean that your server as it stands only supports a single client. But that's a problem that can be addressed later. :)

Seems to have done the trick. Thanks so much!

Boris Galerkin
Dec 17, 2011

I don't understand why I can't harass people online. Seriously, somebody please explain why I shouldn't be allowed to stalk others on social media!
PyCharm question: I have it set to automatically type two ' symbols so it's really convenient. But what's a bit silly is that there doesn't seem to be a "exit" the quotation level if that makes sense, without actually pressing ' again. This gets kind of annoying when I'm trying to use something from a dict because what's the point of it automatically closing the [ and ' symbols if I still need to press those two buttons.

Is there a shortcut I'm missing? I would have guessed alt/ctrl enter or something but that doesn't work.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

End?

Boris Galerkin
Dec 17, 2011

I don't understand why I can't harass people online. Seriously, somebody please explain why I shouldn't be allowed to stalk others on social media!
I don't have that key on my keyboard.

Blinkz0rz
May 27, 2001

MY CONTEMPT FOR MY OWN EMPLOYEES IS ONLY MATCHED BY MY LOVE FOR TOM BRADY'S SWEATY MAGA BALLS
⌘ + ->

huhu
Feb 24, 2006
I'm having a Pycharm or Python issue...
code:
from foo import bar

def test(input):
    myBar = bar()
    return myBar.myMethod(input)

AttributeError: 'bar' object has no attribute 'myMethod'
If I click on myMethod() and navigate to where it is originally declared, it opens the file foo and goes to the bar definition. What am I missing here?

Edit: It's a Pycharm issue. I renamed the directory and reopened it in Pycharm and it's working now. Any ideas what I might triggered by renaming the directory?

huhu fucked around with this message at 16:18 on May 1, 2017

NtotheTC
Dec 31, 2007


huhu posted:

I'm having a Pycharm or Python issue...
code:
from foo import bar

def test(input):
    myBar = bar()
    return myBar.myMethod(input)

AttributeError: 'bar' object has no attribute 'myMethod'
If I click on myMethod() and navigate to where it is originally declared, it opens the file foo and goes to the bar definition. What am I missing here?

Edit: It's a Pycharm issue. I renamed the directory and reopened it in Pycharm and it's working now. Any ideas what I might triggered by renaming the directory?

Was the file actually named "foo" and the class "bar"? If not its possible you named your file something that was already taken by standard lib or an external library. Is the file in the same directory as the file you're importing into? Try
code:
from .foo import bar

huhu
Feb 24, 2006

NtotheTC posted:

Was the file actually named "foo" and the class "bar"? If not its possible you named your file something that was already taken by standard lib or an external library. Is the file in the same directory as the file you're importing into? Try
code:
from .foo import bar

Somehow between yesterday and today, and renaming the folder back to its original name, the issue is gone. This is good to know for next time though.

huhu
Feb 24, 2006
Anyone have any good resources for getting started using extensions (C/C++) with Python? I'm taking over a script that uses this and the most complicated C++ I've written has been for Arduino so I'm not really sure what I'm doing.

Space Kablooey
May 6, 2009


The liquor store?

huhu
Feb 24, 2006

HardDiskD posted:

The liquor store?

Is it that confusing?

tminz
Jul 1, 2004
Total beginner here, hung up on something that I assume is pretty straightforward but can't quite figure it out. Trying to pull a string from an HTML5 data-* attribute using beautiful soup and having some trouble.

I used this:

import requests
from bs4 import BeautifulSoup

r = requests.get('https://finance.yahoo.com/losers')
soup = BeautifulSoup(r.content)
x = soup.find_all("a", class_="Fw(b)")
print(x)

To get me down to this:

<a class="Fw(b)" data-reactid="56" data-symbol="APHB" href="/quote/APHB?p=APHB" title="AmpliPhi Biosciences Corporation">APHB</a>

What I want to do is pull the string "APHB" from the data-symbol attribute for a list of stocks but not sure how to go about it. I've also tried:

x = soup.find_all(attrs={"data-symbol") without much luck.

I feel like I'm going down a convoluted path and theres an easier way to just directly grab from data-symbol.

SurgicalOntologist
Jun 17, 2004

x is the element (in your first code chunk), to get its data-symbol attribute, do x.attrs['data-symbol']. Using attrs in find_all would be for the use case of finding an element that had a specific data-symbol. Or, you could do something along those lines to get all the elements that have that attribute at all. But if you are already able to get the element itself another way, it's straightforward to grab any attribute.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Your first version should be fine, you just need to realise that find_all returns a list (even if there's only 1 or even 0 results). So once you get your list of matching elements, then you need to pull out the data you want from each of them, like with a for loop or a list comprehension


Python code:

symbols = [x.attrs['data-symbol'] for x in soup.find_all("a", class_="Fw(b)")]

This assumes the attr is always present, if you want safety you should use the get method on the attrs dictionary and handle the None values, or filter your find/select so it only returns elements with that attr, something like that. CSS selectors are great

baka kaba fucked around with this message at 12:12 on May 6, 2017

2nd Rate Poster
Mar 25, 2004

i started a joke

huhu posted:

Anyone have any good resources for getting started using extensions (C/C++) with Python? I'm taking over a script that uses this and the most complicated C++ I've written has been for Arduino so I'm not really sure what I'm doing.

The python docs are actually pretty good for this.
https://docs.python.org/3.6/extending/extending.html

underage at the vape shop
May 11, 2011

by Cyrano4747
So I'm doing some rss stuff for Uni. Howcome sometimes the formatting of quotes gets changed and sometimes it doesn't?

This RSS works fine:
https://www.seicane.com/rss/catalog/category/cid/158/store_id/1/

This one doesn't:
https://www.etsy.com/au/shop/OlivineAtelier/rss

I need to extract the price with regular expressions. For some reason, it's changing all the quotes in the second rss to " instead of leaving them as is. How do I make it not do that? Its ruining my regular expressions.

spiritual bypass
Feb 19, 2008

Grimey Drawer
The one with the hosed up quotes has run all their output through an html entity filter for some reason. You can probably find a function somewhere in the Python standard library that'll turn them all back. Once you have the output setup to look like html, you'll probably want to use an html parsing library instead of applying regexes to it. Regex is pretty much always the wrong way to parse a tree structured document (unless that's what your professor has demanded of you).

onionradish
Jul 6, 2006

That's spicy.

underage at the vape shop posted:

So I'm doing some rss stuff for Uni. Howcome sometimes the formatting of quotes gets changed and sometimes it doesn't?
Since RSS is XML, in order to include HTML in the entries, they're escaped. The first link is encoded using CDATA, the second one just does HTML entity escaping.

If you're allowed to use third-party libraries, use feedparser anytime you have to deal with RSS. It handles all the complexity of the RSS variants including namespaces and gives you a standardized dictionary.

If not, you'll need to detect which escaping method has been used and use the stdlib to unescape those like the second type.

In python 2, it's:
code:
from HTMLParser import HTMLParser
clean = HTMLParser().unescape(html_to_unescape)
In python 3, it's:
code:
import html
clean = html.unescape(html_to_unescape)

underage at the vape shop
May 11, 2011

by Cyrano4747
It says in the assignment task sheet that you CAN do it without regex "but it will be very hard to build a robust solution without it". There's an extra feature worth about 20% of the assignment they don't release until like 2 days before its due, to test how we work under ~time limits~, so I think I should. Also we aren't allowed to import any modules that they don't include in the template. I think they wanted an assignment where you use tkinter and regex.

I'll ask in the next workshop what to do about formatting stuff like this. There's some unicode issues too which I dealt with but it's not something they've taught us about at all.

I managed to get it working with other options, but I ran into another issue. We have to have a loading message type thing that changes as it goes through the different RSS feeds and loads your data. Mine doesn't and I can't figure out why

code:
    loading_text.set('Loading Car Parts')
    print loading_text.get()
    carparts=RSS_Scraper(car_parts_rss,int(carparts_spin.get()))
   
    loading_text.set('Loading Safes')
    print loading_text.get()
    safes=RSS_Scraper(safes_rss,int(safes_spin.get()))
    
    loading_text.set('Loading Pillows')
    print loading_text.get()
    pillows=RSS_Scraper(pillows_rss,int(pillows_spin.get()))
    loading_text.set('Done')
You enter in how many items you want from each RSS with spinboxes. You then press a button, and this is the first bit of the function. What should happen, is that the label updates as it loads each RSS. I can see the variable updating in the console with multi second intervals. But on the GUI it stays blank until the end, at which point it changes to done. I tried doing it as loading_label['text'] but that had the same result. I tried putting the text update in the RSS_Scraper function but it didn't work either.

underage at the vape shop fucked around with this message at 15:19 on May 8, 2017

breaks
May 12, 2001

So basically what's happening there is that tkinter is only going to paint the GUI at some point in its event loop, but because that's one continuous section of code the event loop doesn't get a chance to execute until it's finished, leading to the behavior you see.

It's been way too long since I've used tkinter to offer a good solution but what you probably shouldn't do is try to force a paint in that code. This is a common situation and tkinter probably offers some Proper Way of allowing you to break that up so that the event loop gets to execute often enough to see your updates, which hopefully doesn't involve threading.

FoiledAgain
May 6, 2007

underage at the vape shop posted:

You enter in how many items you want from each RSS with spinboxes. You then press a button, and this is the first bit of the function. What should happen, is that the label updates as it loads each RSS. I can see the variable updating in the console with multi second intervals. But on the GUI it stays blank until the end, at which point it changes to done. I tried doing it as loading_label['text'] but that had the same result. I tried putting the text update in the RSS_Scraper function but it didn't work either.

I haven't used tkinter in a few years, and I don't know what the rest of your code looks like, but this sounds like the place for a using a StringVar and the textvariable argument on widgets. Set up your label like this:

code:
label_text = StringVar()
label = Label(master, textvariable = label_text)
label.pack()
Whenever the value of label_text changes, the actual text on the label should change too. Pass label_text to your RSS_Scraper, and make sure its value is appropriately updated.

spiritual bypass
Feb 19, 2008

Grimey Drawer
I've inherited a Python project at work, which is fun. Unfortunately, I'm getting a fatal error with no line number attached. I'm pretty sure I know how to fix it if only I knew where it was happening.
What are some possible reasons I lack a line number and how can I get one?
code:
There was an error: a bytes-like object is required, not 'str'

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
This message is almost certainly not from the Python interpreter itself:

rt4 posted:

code:
There was an error:

It's more likely that somewhere in the code, there's a try/except block that's catching an exception and only printing out the exception's message, like:
Python code:
try:
    # some stuff here
except SomeExceptionType as e:
    # afaik e.message is deprecated or removed
    print(e.args[0])
You could add a bare raise inside whatever appropriate except block to have the exception propagate upward, which will cause the Python interpreter to show you the full traceback (with line numbers, function names, and file names).

spiritual bypass
Feb 19, 2008

Grimey Drawer
Thanks, that's a huge help. For some reason I missed this in the code:
code:
    # Uh-oh! Let's try to cleanup...
    except Exception as e:
        shutil.rmtree(os.path.join(location, name))
        print('There was an error: {}'.format(e))
Chained exceptions are the loving way to go, no doubt

Adbot
ADBOT LOVES YOU

QuarkJets
Sep 8, 2008

Probably execution is supposed to stop at that point, once the error is raised? Definitely throw a raise at the end of that except, if so

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply