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
Slimchandi
May 13, 2005
That finger on your temple is the barrel of my raygun

Thermopyle posted:

Here's a neat thing if you're one of the cool people like me who can mostly move most of their projects to keep up with the latest python versions. Coming in Python 3.7 are data classes!

There's already a backport to 3.6. The __post_init__ method is a nice addition too, if you want to do more in-place data wrangling.

https://pypi.python.org/pypi/dataclasses/

Adbot
ADBOT LOVES YOU

Nippashish
Nov 2, 2005

Let me see you dance!

ZarathustraFollower posted:

filename=('HeteroFreq2.txt'),

What am I doing wrong with declaring the filename?

That comma one the end makes it a tuple with one element. Delete the comma (and maybe also the parens because they're not doing anything).

Dr Subterfuge
Aug 31, 2005

TIME TO ROC N' ROLL

Thermopyle posted:

Here's a neat thing if you're one of the cool people like me who can mostly move most of their projects to keep up with the latest python versions. Coming in Python 3.7 are data classes!


Say I have a program that uses a dictionary to pass data between functions. But at this point it's getting unwieldy, and attribute access sounds more appealing. Is there something in PyCharm that makes that refactoring less painful?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. Bertrand Russell

Dr Subterfuge posted:

Say I have a program that uses a dictionary to pass data between functions. But at this point it's getting unwieldy, and attribute access sounds more appealing. Is there something in PyCharm that makes that refactoring less painful?

I can't think of anything specific to PyCharm that would make that easier other than maybe some fancy regex search/replace.

You can write a class and override the appropriate dunder methods for attribute access...or you can use a library like Box which allows you to access your dict via attribute or item access. That would allow you to keep your functions as is and slowly convert them over to dotted access.

That being said, I'm not convinced it's a good idea. On the one hand, I also find dotted access smoother and less irritating to use, but on the other hand the way you access dicts and the way you access objects is an established thing in Python-land.

Whatever you do, I don't think there's an easy way to refactor this.

I've done the method where I implement the appropriate dunder methods on a class to let me access a dict via attribute and the bad part when it comes to PyCharm is that you don't get any help on autocompletion since the attributes are dynamic in nature.

Seventh Arrow
Jan 26, 2005

So I made the needed adjustments to my folium script and I still wasn't seeing the map appear in jupyter. But apparently this is just down to jupyter being dumb sometimes, so someone on the folium message boards suggested something called "nbviewer", and now it finally works:

http://nbviewer.jupyter.org/gist/ocefpaf/a9afd09bea76bda67b5bf3e0961c30f5

edit: still using iterrows because I think I'm too dense to figure out the alternatives

Space Kablooey
May 6, 2009


So a friend of mine is about to start a Python programming job, and he asked me if I had any Python beginner resources. I recommended Fluent Python and Think Python, but I'm not sure if there's more than that that's highly recommended.

Fake edit: Nevermind, I found this huge list in the Python website: https://wiki.python.org/moin/BeginnersGuide/Programmers

Space Kablooey fucked around with this message at 03:22 on Jan 26, 2018

The March Hare
Oct 15, 2006

Je rve d'un
Wayne's World 3
Buglord
So I've got one I've never had to deal with before that I'm really struggling to google or even figure out.

I'm working on writing a slackbot and I'm printing out a list of usernames. One of my users has a Hebrew name.

code:
response = ''.join(
    [
        '{}: {} - {}$\n'.format(i+1, wallet.owner.name, wallet.balance)
        for i, balance in enumerate(some_list)
    ]
)

print response

>> 
1: Rick - 100$
2: Chloe - 4000$
3: 123 - HEBREW_NAME$
4: Charley - 99$
5: Brynhildr - 400000$ 
For whatever reason, when you format Hebrew (which is written <- instead of ->) it just swaps the number with the name, but doesn't seem to move the $ that follows. Can someone enlighten me on how to fix this?

e: Python 2.7, unicode is a trash fire. I printed the output to the terminal. Here are screenshots of how Slack and iterm2 parse the string, as well as the raw output.




u'1: \u03bb - 0.2712889rc\n2: \u03b1 - 0.16032rc\n3: \u03a9 - 0.12084rc\n4: lamellafella - 0.11516rc\n5: jambonn\xe9 - 0.10515rc\n6: sean - 0.10371rc\n7: \u05d2\u05d5\u05dc\u05dd - 0.06084rc\n8: heidegrrrl - 0.06046rc\n9: nera - 0.0318611rc\n10: hav\xe6\xf1t - 0.02973rc\n'

Taken as raw symbolic order, the Hebrew is not in the correct order in the string. \u05d2\u05d5\u05dc\u05dd if translated in place would be the Hebrew word but in reverse. I guess Slack is correctly reversing it, but iterm is not. The question, though, is why is it swapping the position of the name and the number...

The March Hare fucked around with this message at 04:03 on Jan 26, 2018

tef
May 30, 2004

-> some l-system crap ->
Stick a \u200E in it

https://www.w3.org/International/questions/qa-bidi-unicode-controls

The March Hare
Oct 15, 2006

Je rve d'un
Wayne's World 3
Buglord

I'm not sure I would have ever figured this out, thank you.

tef
May 30, 2004

-> some l-system crap ->
What's messing up is the bidi algorithm

in the big table of stuff

http://unicode.org/reports/tr9/#Table_Bidirectional_Character_Types

you can see that numbers are weak, so they're influenced by the text surrounding them.

in this case, some implementations see it as part of the hebrew text because it's just numbers, resetting when the encounter a dollar sign, others recognize it as belonging to the dollar sign, or surrouding letters

The March Hare
Oct 15, 2006

Je rve d'un
Wayne's World 3
Buglord

tef posted:

What's messing up is the bidi algorithm

in the big table of stuff

http://unicode.org/reports/tr9/#Table_Bidirectional_Character_Types

you can see that numbers are weak, so they're influenced by the text surrounding them.

in this case, some implementations see it as part of the hebrew text because it's just numbers, resetting when the encounter a dollar sign, others recognize it as belonging to the dollar sign, or surrouding letters

Yeah, I just tossed the hard ltr char right after the name and it looks fine now. Thanks~

Dr Subterfuge
Aug 31, 2005

TIME TO ROC N' ROLL

Thermopyle posted:

I can't think of anything specific to PyCharm that would make that easier other than maybe some fancy regex search/replace.

You can write a class and override the appropriate dunder methods for attribute access...or you can use a library like Box which allows you to access your dict via attribute or item access. That would allow you to keep your functions as is and slowly convert them over to dotted access.

That being said, I'm not convinced it's a good idea. On the one hand, I also find dotted access smoother and less irritating to use, but on the other hand the way you access dicts and the way you access objects is an established thing in Python-land.

Whatever you do, I don't think there's an easy way to refactor this.

I've done the method where I implement the appropriate dunder methods on a class to let me access a dict via attribute and the bad part when it comes to PyCharm is that you don't get any help on autocompletion since the attributes are dynamic in nature.

Well you've given me the idea of just running a regex script on the files themselves that subs out a bracketed key in the code for the dotted equivalent. Shouldn't be too hard to make a pattern for, at least for the majority of cases. Hopefully. At least it gives me an excuse to mess with functional replacement in re.sub. Thanks!

tef
May 30, 2004

-> some l-system crap ->

The March Hare posted:

Yeah, I just tossed the hard ltr char right after the name and it looks fine now. Thanks~

code:
>>> import unicodedata
>>> def wrap_rtl(name):
...     if unicodedata.bidirectional(name[0]):
...             return "\u200f{}\u200e".format(name)
...     else:
...             return name
... 
>>> name ="\u05dd\u05dc\u05d5\u05d2"
>>> 
>>> print("hi {} 123 hi".format(name))
hi 123 ... hi
>>> print("hi {} 123 hi".format(wrap_rtl(name)))
hi ... 123 hi
:toot:

Wallet
Jun 19, 2006

I have another potentially stupid question that I can hopefully explain in something resembling a comprehensible fashion:

Let's say I have a paragraph of text with hard line breaks in a list, with each line as an item:
code:
['There was no hope for him this time: it was the third stroke. Night',
'after night I had passed the house (it was vacation time) and studied',
'the lighted square of window: and night after night I had found it lighted',
'in the same way, faintly and evenly. If he was dead, I thought, I would see',
'the reflection of candles on the darkened blind for I knew that two candles',
'must be set at the head of a corpse.']
And I generate a separate list that is storing that text as sentences:
code:
['There was no hope for him this time: it was the third stroke.',
'Night after night I had passed the house (it was vacation time) and studied the lighted square of window: and night after night I had found it lighted in the same way, faintly and evenly.',
'If he was dead, I thought, I would see the reflection of candles on the darkened blind for I knew that two candles must be set at the head of a corpse.']
And I want to do some stuff with the sentences. Like, for an arbitrary example, let's say that I want to count the number of letters in each word in the sentences. To be clear, the actual stuff I'm doing requires that the text be broken out into sentences. Let's say I'm storing the counts in nested lists:
code:
[[5, 3, 2, 4, 3, 3, 4, 4, 2, 3, 3, 5, 6], [5, 5, 5, 1, 3, ...], [...]]
Now, let's say that I want to insert those letter counts back into the original version that was broken up by lines, which might look something like this (pretend I did the whole thing):
code:
['There{5} was{3} no{2} hope{4} for{3} him{3} this{4} time{4}: it{2} was{3} the{3} third{5} stroke{6}. Night{5},',
'after{5} night{5}...']
Is there some clever way to accomplish this? The best I can come up with is using word count/position to sort of reconstruct where the numbers should be inserted, since the third word in the sentence version is still the third word in the line version, but I dunno if I'm missing something.

Jose Cuervo
Aug 25, 2004

Wallet posted:

I have another potentially stupid question that I can hopefully explain in something resembling a comprehensible fashion:

Let's say I have a paragraph of text with hard line breaks in a list, with each line as an item:
code:
['There was no hope for him this time: it was the third stroke. Night',
'after night I had passed the house (it was vacation time) and studied',
'the lighted square of window: and night after night I had found it lighted',
'in the same way, faintly and evenly. If he was dead, I thought, I would see',
'the reflection of candles on the darkened blind for I knew that two candles',
'must be set at the head of a corpse.']
And I generate a separate list that is storing that text as sentences:
code:
['There was no hope for him this time: it was the third stroke.',
'Night after night I had passed the house (it was vacation time) and studied the lighted square of window: and night after night I had found it lighted in the same way, faintly and evenly.',
'If he was dead, I thought, I would see the reflection of candles on the darkened blind for I knew that two candles must be set at the head of a corpse.']
And I want to do some stuff with the sentences. Like, for an arbitrary example, let's say that I want to count the number of letters in each word in the sentences. To be clear, the actual stuff I'm doing requires that the text be broken out into sentences. Let's say I'm storing the counts in nested lists:
code:
[[5, 3, 2, 4, 3, 3, 4, 4, 2, 3, 3, 5, 6], [5, 5, 5, 1, 3, ...], [...]]
Now, let's say that I want to insert those letter counts back into the original version that was broken up by lines, which might look something like this (pretend I did the whole thing):
code:
['There{5} was{3} no{2} hope{4} for{3} him{3} this{4} time{4}: it{2} was{3} the{3} third{5} stroke{6}. Night{5},',
'after{5} night{5}...']
Is there some clever way to accomplish this? The best I can come up with is using word count/position to sort of reconstruct where the numbers should be inserted, since the third word in the sentence version is still the third word in the line version, but I dunno if I'm missing something.

You could generate a single list of all the numbers, then iterate through the original lines, and for each word on each of the original lines, pop a number from the single list to attach to the end of the word.

Edit: Something along these lines:
Python code:
new_text = ''
for line in all_lines:
    for word in line:
        new_text += word + '{' + str(all_numbers.pop(0)) + '} '
    new_text += '\n'

Jose Cuervo fucked around with this message at 15:01 on Jan 26, 2018

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

The easiest thing would be to add the numbers as you do the counting - I'm guessing you're splitting the sentence on whitespace, and doing something smart about punctuation, so that would be a good time to decide where the count should go (like it needs to go before that colon in the first sentence, but apostrophes would be treated differently etc). So you'd take each word, count it, then transform the string to add the count, and eventually just use join to put it all back together

If you're in the situation where the counts have already been done, you just need to get back to that state again - split each sentence into words. Then you'll have two structures that mirror each other (a list of lists of words, and a list of lists of counts), and you can iterate over those together, using zip to get pairs of word lists and count lists, and using zip again on those to get pairs of words and counts

tldr you're probably looking for zip

Wallet
Jun 19, 2006

Thanks for the responses guys, that's more or less what I was thinking but I wasn't sure if I was missing a super clever approach. I will have to look into zip, however, as I wasn't aware of it and it seems extremely useful.

wasey
Apr 6, 2009
Is this a place for stupid newbie Python questions? I am working on a class assignment where I have to use a dynamic programming implementation of the make change problem. The algorithm is fine if I hard code values into it, but I'm having a hard time reading data from the required text file and using that data. Input .txt file looks like this:
code:
1 2 5		#the denominations in this set
10		#total amount, break this number and previous denomination set
1 3 7 12	#new denomination set
29		#new amount, etc
1 2 4 8
15
I'm parsing the data into two arrays, one called coin array which contains
code:
 [['1 2 5'], ['1 3 7 12'], ['1 2 4 8']]
and one called change which contains
code:
 [['10 29 15']]
I can access data in the change array without issue (e.g. change[2] = 15) but when I try the same thing with the coin array, I get the error
code:
    for j in [int(coinVal) for coinVal in coinValueList if coinVal <= cents]:
TypeError: unorderable types: str() <= int() 
I'm trying to cast everything as an integer but obviously that isn't working... Here is the full function:
code:
def makeChange(coinValueList,change,minCoins,coinsUsed):
   for cents in range(change + 1):
      coinCount = cents
      newCoin = 1
      for j in [int(coinVal) for coinVal in coinValueList if coinVal <= cents]:
            if minCoins[cents - j] + 1 < coinCount:
               coinCount = minCoins[cents - j] + 1
               newCoin = j
      minCoins[cents] = coinCount
      coinsUsed[cents] = newCoin
   return minCoins[change]
I've only been using Python for about three weeks and am getting stuck on a lot of syntax issues. Any suggestions? Thank you!

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

If you look at the error, it's saying you can't do str() <= int(), and there's something that looks like that in the line it quoted

you're casting to int after you've done the comparison - you need to get used to the order it's written in python, but it does the for bit to get items, then the if bit to filter them, and then it does the bit on the left with the results.

You can think of the for part as item from items (where item passes this test)

wasey
Apr 6, 2009

baka kaba posted:

If you look at the error, it's saying you can't do str() <= int(), and there's something that looks like that in the line it quoted

you're casting to int after you've done the comparison - you need to get used to the order it's written in python, but it does the for bit to get items, then the if bit to filter them, and then it does the bit on the left with the results.

You can think of the for part as item from items (where item passes this test)


Got it working, thanks for your explanation on the for/if!

Wallet
Jun 19, 2006

Is there any reason you're storing the data you're reading in as strings instead of integers?

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

Yeah ideally you'd convert all that as you parse it. Read in each line, split it and convert each item to an int. That way your "get input" part hands you a pristine set of int lists, which is the structure you want to work with

Portland Sucks
Dec 21, 2004
༼ つ ◕_◕ ༽つ
I'm working on converting a sequence of calculations done in an Excel workbook into a python script so we can automate the process. I've been writing tests for each function where the function represents an algorithm for one computation (interpolation, some PDEs, etc...) typically with an input of a few lists and an output of a new list. The issue I'm having is that I keep getting varying amounts of precision loss throughout the process when comparing my results to the output results of the Excel computations. I'm working with values that need to be precise out to about 6 decimal places, but python seems to handle floating points somewhat arbitrarily?

For example I load in a list of values that look like 0, .25, .5, 1, 1.25, 1.5, etc... in Excel and my resulting python list is 0, .25, .4999999999999, 1, 1.249999999999993, 1.5, etc...

I know floating point math is a nontrivial issue, but is there a standard way to handle this stuff when doing routine calculations on numbers that are very precise? My current thought is to just change my tests to pass if there is less than n% difference between the Excel values and the python computed values, but that seems a little hand wavy.

Eela6
May 25, 2007
Shredded Hen
If you want arbitrary precision, you should use the decimal library.

Alternately, use math.isclose()

pmchem
Jan 22, 2010


Portland Sucks posted:

I know floating point math is a nontrivial issue, but

Welcome to the wonderful world of floating point:
https://en.wikipedia.org/wiki/IEEE_754#Basic_and_interchange_formats
https://docs.python.org/3.7/tutorial/floatingpoint.html

But you probably want,

https://www.python.org/dev/peps/pep-0485/
https://docs.python.org/3/library/math.html see isclose()

Nippashish
Nov 2, 2005

Let me see you dance!

Portland Sucks posted:

I know floating point math is a nontrivial issue, but is there a standard way to handle this stuff when doing routine calculations on numbers that are very precise? My current thought is to just change my tests to pass if there is less than n% difference between the Excel values and the python computed values, but that seems a little hand wavy.

You're opening a huge can of worms here by asking about precision, although almost certainly the answer you want is "learn to live with small amounts of precision difference".

However, if you're seeing differences as early as just reading the values and looking at what you read it is extremely likely that excel actually has the same precision loss as python and is just rounding differently for display purposes.

Portland Sucks
Dec 21, 2004
༼ つ ◕_◕ ༽つ

Got it, I guess this is pretty much how I was attempting to write my tests. I figured that Excel likely had precision loss in it as well and I know the guy who originally wrote the Excel workbook we're using put no thought into what he was doing regarding precision. I just want to make sure that what I'm producing isn't going to be wildly off the mark.

accipter
Sep 12, 2003

Portland Sucks posted:

Got it, I guess this is pretty much how I was attempting to write my tests. I figured that Excel likely had precision loss in it as well and I know the guy who originally wrote the Excel workbook we're using put no thought into what he was doing regarding precision. I just want to make sure that what I'm producing isn't going to be wildly off the mark.

Also take a look at numpy.testing.assert_allclose for testing all values in an array.

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!
e: misread

Boris Galerkin fucked around with this message at 09:38 on Jan 30, 2018

porksmash
Sep 30, 2008
Does anyone have experience mirroring PyPi? My work is about to shut off all internet access to internal servers as a security measure, and are working on setting up internal package mirrors for everything we use. I think they're more concerned about the internet connection than malicious packages, which is lucky for me. I'm leaning towards a caching PyPi proxy server like devpi-server rather than an actual mirror of the entire index.

Hadlock
Nov 9, 2004

Is there a package/library similar to Go's "Cobra"? Command line flagging coffee organizational thing.

Tigren
Oct 3, 2003

Hadlock posted:

Is there a package/library similar to Go's "Cobra"? Command line flagging coffee organizational thing.

I'm not sure you're gonna find something exactly like cobra, but maybe check out Click

Python code:
import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
              help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo('Hello %s!' % name)

if __name__ == '__main__':
    hello()
Bash code:
#And what it looks like when run:

$ python hello.py --count=3
Your name: John
Hello John!
Hello John!
Hello John!

# It automatically generates nicely formatted help pages:

$ python hello.py --help
Usage: hello.py [OPTIONS]

  Simple program that greets NAME for a total of COUNT times.

Options:
  --count INTEGER  Number of greetings.
  --name TEXT      The person to greet.
  --help           Show this message and exit.

mr_package
Jun 13, 2000
When deploying Flask with gunicorn gevent workers do I need to worry about the concurrency of the user session (using the built in module flask.session)? Or is this handled by Flask (Werkzeug) already?

Edit: Looks like it doesn't matter; session is saved by the browser so Flask has no 'state' of user sessions to maintain. Based on the answer here:
https://stackoverflow.com/questions/38427923/how-does-flask-sessions-work

mr_package fucked around with this message at 00:19 on Jan 31, 2018

SurgicalOntologist
Jun 17, 2004

Hadlock posted:

Is there a package/library similar to Go's "Cobra"? Command line flagging coffee organizational thing.

I personally like docopt, although many prefer click. For docopt, you write the help message first (as a docstring), and docopt parses it. Tigren's example would look something like (modifying it to show positional args and flagged options).
Python code:
"""hello.py

Simple program that greets <name> for a total of N times.

Usage:
  hello.py [OPTIONS] <name>


Options:
  --help -h      Show this message.
  --count=N       Number of greetings [default: 1].

"""
from docopt import docopt


def hello(name, count=1):
    for x in range(count):
        print(f'Hello {name}!')


def main():
    args = docopt(__doc__)
    hello(args['-<name>], count=int(args['--count']))


if __name__ == '__main__':
    main()
As you can see, you have to do some parsing yourself, but I find its ease to make up for it.

Hadlock
Nov 9, 2004

Yeah click looks like exactly what I'm looking for. Docopts looks useful but click, i read the example and that seems very easy to work with.

Has anyone ever mixed and matched flask with click? I have a bunch of baby services I'll need to write for a project and my coworkers are still stuck doing cli stuff and haven't graduated fully to api. I thought maybe I could setup the app as a flask api service, but could also be run from the command line if well documented to give my coworkers a chance to come up to speed.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. Bertrand Russell

Hadlock posted:

Yeah click looks like exactly what I'm looking for. Docopts looks useful but click, i read the example and that seems very easy to work with.

Has anyone ever mixed and matched flask with click? I have a bunch of baby services I'll need to write for a project and my coworkers are still stuck doing cli stuff and haven't graduated fully to api. I thought maybe I could setup the app as a flask api service, but could also be run from the command line if well documented to give my coworkers a chance to come up to speed.

I've done something similar with Django and argparse.

Pretty easy with django management commands.

SurgicalOntologist
Jun 17, 2004

Hadlock posted:

Has anyone ever mixed and matched flask with click? I have a bunch of baby services I'll need to write for a project and my coworkers are still stuck doing cli stuff and haven't graduated fully to api. I thought maybe I could setup the app as a flask api service, but could also be run from the command line if well documented to give my coworkers a chance to come up to speed.

Click is built into flask already: http://flask.pocoo.org/docs/0.12/cli/ (same author I think)

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 use Python Fire.

quote:

You can call Fire on any Python object:
functions, classes, modules, objects, dictionaries, lists, tuples, etc. They all work!

Here's an example of calling Fire on a class.

code:
import fire

class Calculator(object):
  """A simple calculator class."""

  def double(self, number):
    return 2 * number

if __name__ == '__main__':
  fire.Fire(Calculator)
Then, from the command line, you can run:

code:
python calculator.py double 10  # 20
python calculator.py double --number=15  # 30

Hed
Mar 31, 2004

Fun Shoe

porksmash posted:

Does anyone have experience mirroring PyPi? My work is about to shut off all internet access to internal servers as a security measure, and are working on setting up internal package mirrors for everything we use. I think they're more concerned about the internet connection than malicious packages, which is lucky for me. I'm leaning towards a caching PyPi proxy server like devpi-server rather than an actual mirror of the entire index.

Youve got the right idea. With some of the other methods package searching from pip was wonky, but devpi works pretty well for us.

Adbot
ADBOT LOVES YOU

ArcticZombie
Sep 15, 2010
I'm doing something wrong/misunderstanding how to use asyncio. I want to read from stdin, start a task based on that input and be able to receive more input and start more tasks while waiting for that task to complete. But the first task seems to be blocking and I don't understand why. Here is an distilled example (with load simulating a task taking some time):

Python code:
import asyncio
import sys


async def load():
    await asyncio.sleep(3)
    return "done"


async def listen(loop):
    while True:
        recv = await loop.run_in_executor(None, sys.stdin.readline)
        print(f"Received: {recv}", end="")
        res = await load()
        print(f"Result {recv.strip()}: {res}")

loop = asyncio.get_event_loop()
loop.run_until_complete(listen(loop))
loop.close()
Running this, if I enter:

code:
1
2
I expect:

code:
1
Received: 1
2
Received: 2
Result 1: done
Result 2: done
But what I actually get is:

code:
1
Received: 1
2
Result 1: done
Received: 2
Result 2: done
What am I doing wrong here?

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