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.
 
  • Locked thread
Computer viking
May 30, 2011
Now with less breakage.

Gothmog1065 posted:

I'm not waiting to wait for the command to fully open. Basically my "script" is going to open a few different programs, and leave them open, but I didn't want to slam the computer all at once. But I know some programs take longer than others to open (IE takes forever compared to notepad). If there's not a simpler way to do this, then I'll wait for now.

Ah, right. There's no good generic definition of "done loading" you can wait for, really - so you'll probably have to settle for sleeping a second or some such. If you feel fancy you could monitor CPU and disk activity and launch the next app when it dips?

edit: Never mind, I can't find an easy way to do that on Windows.

Computer viking fucked around with this message at 17:22 on Jan 25, 2012

Adbot
ADBOT LOVES YOU

Gothmog1065
May 14, 2009

Computer viking posted:

Ah, right. There's no good generic definition of "done loading" you can wait for, really - so you'll probably have to settle for sleeping a second or some such. If you feel fancy you could monitor CPU and disk activity and launch the next app when it dips?

That's probably why I didn't find much, as there's not much there. Thanks.

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

Actually, I've monitored both CPU and disk activity in Windows using the Python WMI library. It's not incredibly painful to use, but it might be more than you're looking for.

http://timgolden.me.uk/python/wmi/index.html

Computer viking
May 30, 2011
Now with less breakage.

BeefofAges posted:

Actually, I've monitored both CPU and disk activity in Windows using the Python WMI library. It's not incredibly painful to use, but it might be more than you're looking for.

http://timgolden.me.uk/python/wmi/index.html

Ah, nice - thanks. I don't do much python on windows, but at some point it might be useful. :)

Gothmog1065
May 14, 2009
I'd just like to put in my official thank you. I've asked some really loving stupid questions, but you guys were pretty good about working with me and explaining poo poo. I still don't understand certain things, but after stepping through commands and seeing how they work, I've learned a lot. I actually have a script that works. Whether or not it is properly "scripted" is moot, it works. I still have other things to work on, but again. Thank you!

More stupid loving questions to come!

tripwire
Nov 19, 2004

        ghost flow

Computer viking posted:

...you could monitor CPU and disk activity and launch the next app when it dips?
Unless you don't want it to work for anyone who runs BG processes to suck up idle cycles, like folding@home and the like

Gothmog1065
May 14, 2009
Back to the dumb questions!

Okay, I'm opening a program, say notepad. I want to use %systemroot%\system32 for obvious reasons rather than c:\Windows\System32. The problem is that when it tries to change to that directory, it doesn't exist. Is there a simple way around this?

duck monster
Dec 15, 2004

Gothmog1065 posted:

I'd just like to put in my official thank you. I've asked some really loving stupid questions, but you guys were pretty good about working with me and explaining poo poo. I still don't understand certain things, but after stepping through commands and seeing how they work, I've learned a lot. I actually have a script that works. Whether or not it is properly "scripted" is moot, it works. I still have other things to work on, but again. Thank you!

More stupid loving questions to come!

Theres no such thing as stupid questions, just easy and hard ones. Its the only way to learn.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

duck monster posted:

Theres no such thing as stupid questions

Except for all the ones where a simple search would lead to the answer in the first hit.

Scaevolus
Apr 16, 2007

Gothmog1065 posted:

Back to the dumb questions!

Okay, I'm opening a program, say notepad. I want to use %systemroot%\system32 for obvious reasons rather than c:\Windows\System32. The problem is that when it tries to change to that directory, it doesn't exist. Is there a simple way around this?
os.path.expandvars("%systemroot%\\system32")

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



If you really are running notepad, subprocess.call('notepad.exe') should just work. Windows has a path environment variable, too.

Thermopyle
Jul 1, 2003

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

I'm thinking about using Mark Summerfield's Rapid GUI Programming With Python and Qt (because I have a copy of it for some reason) to learn PyQt and GUI programming. Well, actually I'm learning PySide, but from looking over PySide's site, there's not much difference.

My main questions are:

1. Given that the book was written a few years ago on PyQt 4.2, are there enough differences between 4.2 and modern PyQt (and by extension, PySide) to make this book worthless?

2. If it's not worthless, what are some changes that I should look out for?

3. Is there a book that's better that I should give a try?

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
I'm looking for some general advice on getting a Python REPL working in a GUI. I am doing some stuff with 3d, and kind of want a Python console to plop down when I hit tilde, like one would expect a console generally to be for stuff like that. Is there any existing stuff to do that in Python? I was hoping for some helpers for things like history and getting all the tab indent prompts correct. I had been through doing this somewhat manually in C# before, and found it to be really tedious. So I want to avoid having to start from scratch.

leterip
Aug 25, 2004

Rocko Bonaparte posted:

I'm looking for some general advice on getting a Python REPL working in a GUI. I am doing some stuff with 3d, and kind of want a Python console to plop down when I hit tilde, like one would expect a console generally to be for stuff like that. Is there any existing stuff to do that in Python? I was hoping for some helpers for things like history and getting all the tab indent prompts correct. I had been through doing this somewhat manually in C# before, and found it to be really tedious. So I want to avoid having to start from scratch.

I did a little bit of Googling and if you can throw twisted in there you can use twisted.conch.stdio. Either python -m twisted.conch.stdio or just from twisted.conch import stdio; stdio.main() and you get a nice REPL (it even had syntax coloring for me!)

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
twisted.conch.stdio is really designed for a remote Python prompt. So if you're trying to debug your server from your client and want a Python prompt for that, you should probably use it (of course, that somewhat relies on you having your networking already done through Twisted, but you should already be doing that).

The code module is just the thing if you just want a REPL. You probably want to create a new subclass of InteractiveInterpreter and implement the write method.

Because Python acts the way it usually does, you may need to replace sys.stdout and sys.stderr so that something like print "Foo!" works in your console:

code:
import code
import contextlib
from cStringIO import StringIO

@contextlib.contextmanager
def monkey_patch_stdio():
    import sys
    realstdout, sys.stdout = sys.stdout, StringIO()
    realstderr, sys.stderr = sys.stderr, StringIO()
    yield (sys.stderr, sys.stdout)
    stdout, sys.stdout = sys.stdout, realstdout
    stderr, sys.stderr = sys.stderr, realstderr

class GUIInterpreter(code.InteractiveInterpreter):
    def runsource(self, *a, **kw):
        with monkey_patch_stdio() as (stdout, stderr):
            super(self, GUIInterpreter).runsource(*a, **kw)

Suspicious Dish fucked around with this message at 17:49 on Jan 30, 2012

Xguard86
Nov 22, 2004

"You don't understand his pain. Everywhere he goes he sees women working, wearing pants, speaking in gatherings, voting. Surely they will burn in the white hot flames of Hell"
Odd question: I've been looking into learning python in my free time, its tangentially related to my job but I'm not in IT or development. I majored in MIS in college, so I had basic exposure to coding, CS101 stuff (using java primarily).

I am finding that the basic resources like "Learning Python the Hard way" is pretty simple for me, not trivial but pretty easy to understand and put together. It mostly feels like I'm learning syntax for the logic functions I already know.

However, when I look at real code like what is posted around here, my head spins. All the different modules, interfacing with email servers, and talk of multithreaded hyperdrive cores. How do you jump from "this is a loop, here is a variable, can you make the turtle draw a square?" to:

quote:

twisted.conch.stdio is really designed for a remote Python prompt. So if you're trying to debug your server from your client and want a Python prompt for that, you should probably use it (of course, that somewhat relies on you having your networking already done through Twisted, but you should already be doing that).

The code module is just the thing if you just want a REPL. You probably want to create a new subclass of InteractiveInterpreter and implement the write method.

Because Python acts the way it usually does, you may need to replace sys.stdout and sys.stderr so that something like print "Foo!" works in your console:

duck monster
Dec 15, 2004

Just gently caress around with the standard modules , or a system like Django until you feel your sea-legs for more complex python kicking in.

Really the only places python gets "hard" is when people use the lambda stuff (which incidently Guido van rossen really dislikes but feels its too hard to replace) because of its goofy syntax, and some of the plumbing methods (setter/getter type stuff, etc) in the object model. All of which are handy to know, but completely optional.

Thermopyle
Jul 1, 2003

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

Xguard86 posted:

Odd question: I've been looking into learning python in my free time, its tangentially related to my job but I'm not in IT or development. I majored in MIS in college, so I had basic exposure to coding, CS101 stuff (using java primarily).

I am finding that the basic resources like "Learning Python the Hard way" is pretty simple for me, not trivial but pretty easy to understand and put together. It mostly feels like I'm learning syntax for the logic functions I already know.

However, when I look at real code like what is posted around here, my head spins. All the different modules, interfacing with email servers, and talk of multithreaded hyperdrive cores. How do you jump from "this is a loop, here is a variable, can you make the turtle draw a square?" to:

Most of the stuff you quoted and most of the stuff that you will find confusing comes from 3rd party libraries. The only way to figure that poo poo out is to try using them to solve a problem.

FWIW, I've never been able to understand a thing about Twisted, so you're not alone there. I've started to try to learn it a few times but got a bit into the documentation and just said "gently caress it" and found another, smaller, more-focused library to do what I want.

The Gripper
Sep 14, 2004
i am winner

Xguard86 posted:

Odd question: I've been looking into learning python in my free time, its tangentially related to my job but I'm not in IT or development. I majored in MIS in college, so I had basic exposure to coding, CS101 stuff (using java primarily).

I am finding that the basic resources like "Learning Python the Hard way" is pretty simple for me, not trivial but pretty easy to understand and put together. It mostly feels like I'm learning syntax for the logic functions I already know.

However, when I look at real code like what is posted around here, my head spins. All the different modules, interfacing with email servers, and talk of multithreaded hyperdrive cores. How do you jump from "this is a loop, here is a variable, can you make the turtle draw a square?" to:
I'll freely admit that a lot of what gets said here (and in other threads on languages I have experience in) goes right over my head. Most of it isn't because I don't know enough about python, it's that I haven't had a requirement to do whatever/use whatever library people are talking about. Twisted is a good example, anything people post about that just goes in one ear and out the other despite having done networking in a number of big projects.

There's a lot of things that make sense if you know why it's doing what it does (threading for example) that come across as gibberish to someone that hasn't learned about it in general, regardless of language. Then there are things like Twisted that are on the other side, where the difficulty is that you need to learn Twisted specifically to know what the gently caress is going on because a lot of the more obvious parts are hidden behind reactors and factories (which are named that way by Twisted, not Python).

In short: third party library = learning curve for the library, multithreaded hyperdrive = learning curve for the feature (independent of language).

Edit; ^^^^ exactly how I feel about Twisted, and I've tried a few times to learn it but it gets to a point where the learning curve turns from "oh yeah this makes sense" to "HOLY GOD WHAT WHY".

The Gripper fucked around with this message at 20:38 on Jan 30, 2012

fart simpson
Jul 2, 2005

DEATH TO AMERICA
:xickos:

I figured out Twisted a couple years ago, and then wanted to drag up an old IRC bot I wrote in it but no matter what I did Twisted wouldn't work on my computer anymore. It was the exact same windows XP computer and I just had errors on imports forever no matter what I tried and then I just gave up too.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
Twisted only started to make sense to me after I found myself reinventing it (badly).

This has been the case for most complex frameworks I've used.

Xguard86
Nov 22, 2004

"You don't understand his pain. Everywhere he goes he sees women working, wearing pants, speaking in gatherings, voting. Surely they will burn in the white hot flames of Hell"
well, that actually makes me feel better: knowing its not all common knowledge when people are discussing these libraries.

I guess its just like Plorkyeran above me said, I'll figure it out whenever it becomes something I need.

Not My Leg
Nov 6, 2002

AYN RAND AKBAR!
I'm teaching myself Python and have a pretty basic question (that I am having trouble describing generically, so I'll use an example). I have a game with a variable number of players (2-8). Each player has different characteristics (for the example, let's just use name). I want to set it up so that each player is attached to a variable (player_1, player_2, ... player_n). I can think of one way to actually do this, and one way to do something close enough, but I'm wondering which is more pythonic, or if there is a better way in general to do this. I have essentially no past programming experience, so coding horrors probably follow.

First, use exec, but I have heard people say using exec is a horror (obviously this is a snippet for an example. The class would be more than that, and num_players would be defined somewhere else).

code:
class Player(object):
    def __init__(self):
        self.name = raw_input("Name? >")

for i in range (1, num_players+1):
    exec "player_%i = Player()" %i
Option 2, just stick them in a list. No longer assigned to a specific variable, but easily retrievable from the list.

code:
class Player(object):
    def __init__(self):
        self.name = raw_input("Name? >")

player_list = []
for i in range (0, num_players):
    player_list.append(Player())
Is one of these more "correct" or is there a better way to do this in general? I think I prefer method 2, because it's a little more transparent as to what is going on, but no strong opinion. If I did, for some reason, actually need to assign variable names, would method 1 be "correct"?

Haystack
Jan 23, 2005





Option two is definitely the way to go. Dynamically created variables are a pain in the rear end to deal with.

Opinion Haver
Apr 9, 2007

Never use eval() unless you fully intend to actually execute code because you're, say, writing an IRC bot that can load plugins on the fly.

No Safe Word
Feb 26, 2005

yaoi prophet posted:

Never use eval() unless you fully intend to actually execute code because you're, say, writing an IRC bot that can load plugins on the fly.

Even then don't use it. Use something like imp

Eliza
Feb 20, 2011

Not My Leg posted:

Is one of these more "correct" or is there a better way to do this in general? I think I prefer method 2, because it's a little more transparent as to what is going on, but no strong opinion. If I did, for some reason, actually need to assign variable names, would method 1 be "correct"?

A better way of dealing with this might be to define a dictionary holding the player objects, with player designation as the key ('player_1' for instance). You could pull the necessary objects from the list, and use it like a variable anyway. You could even have different referral names for the same object if necessary (it's not).

Also, try to avoid user interaction in the constructor - just have a function do the user interaction and then create the object from whatever is input. You can check for validity (length, symbols, etc.) before creating the actual object that way.

code:
def create_player():
    def validate (checkthis):
        # validation...
        if checkthis is not None and len(checkthis) > 0:
            cur_name = checkthis
            return True
        print 'Please check your input.'
        return False

    cur_name = None
    while (!validate(cur_name)) # Check whether it conforms to whatever you expect of it
        cur_nameraw_input("Player name: ")
    playerdict['player_1'] = Player(cur_name)
There are probably several hidden horrors in there, but I think you get the idea.

Edit: Changed things around to remain in their own scope.

Eliza fucked around with this message at 23:03 on Jan 30, 2012

Not My Leg
Nov 6, 2002

AYN RAND AKBAR!

Eliza posted:

A better way of dealing with this might be to define a dictionary holding the player objects, with player designation as the key ('player_1' for instance). You could pull the necessary objects from the list, and use it like a variable anyway. You could even have different referral names for the same object if necessary (it's not).

Also, try to avoid user interaction in the constructor - just have a function do the user interaction and then create the object from whatever is input. You can check for validity (length, symbols, etc.) before creating the actual object that way.

code:
def create_player():
    def validate (checkthis):
        # validation...
        cur_name = checkthis
        return True

    cur_name = None
    while (!validate(raw_input())) # Check whether it conforms to whatever you expect of it
        print 'Please check your input.'
    playerdict['player_1'] = Player(cur_name)
There are probably several hidden horrors in there, but I think you get the idea.

Completely agree about using the function to get the user input, rather sticking it in the constructor.

As for the dict, would this be the best way to do that for multiple players (obviously I would want each player to be indexed under the proper player number)?

code:
def create_player(num_players):
    def validate (checkthis):
        # validation...
        cur_name = checkthis
        return True

    for i in range (0, num_players):
        player = 'player_%i' % (i+1)
        cur_name = None
        while (!validate(raw_input())) # Check whether it conforms to whatever you expect of it
            print 'Please check your input.'
        playerdict[player] = Player(cur_name)
Or is this bad for some reason?

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!

Suspicious Dish posted:

The code module is just the thing if you just want a REPL. You probably want to create a new subclass of InteractiveInterpreter and implement the write method.
Yes this looks perfect! Has anybody told you how wonderful you are lately?

fart simpson
Jul 2, 2005

DEATH TO AMERICA
:xickos:

haha I don't mean to be mean because I think I did something like this before too, but
code:
for i in range (1, num_players+1):
    exec "player_%i = Player()" %i
is horrifying

Not My Leg
Nov 6, 2002

AYN RAND AKBAR!

MeramJert posted:

haha I don't mean to be mean because I think I did something like this before too, but
code:
for i in range (1, num_players+1):
    exec "player_%i = Player()" %i
is horrifying

Oh, I take no offense, I have literally no idea what I am doing and still knew enough to think that was probably horrifying. I had just seen someone (no idea where, probably stack overflow) suggest that was the correct solution, and I thought "that works, but can't be right."

tef
May 30, 2004

-> some l-system crap ->

Plorkyeran posted:

Twisted only started to make sense to me after I found myself reinventing it (badly).

This has been the case for most complex frameworks I've used.

twisted I find is more an abstraction around an event loop over an abstraction useful for writing event driven code -- i.e it is more convenient for the twisted maintainers than the users. I find myself more attached to the co-routine style (PEP-342) things which have started to appear (monocle, bluelet and even in twisted (but undocumented, of course)).

as for reinventing things - it reminds me of jwz's rant on mail summary files http://www.jwz.org/doc/mailsum.html

Xguard86 posted:

How do you jump from "this is a loop, here is a variable, can you make the turtle draw a square?" to:

You don't jump, you crawl. You can pick up python quickly, but understanding the mechanics takes much longer. Much of the more in-depth features are ways of exposing a simpler interface to library users - you don't need to understand the descriptor protocol or other special methods to use objects that use them.

My suggestion would not be to try and write python that takes advantages of these things, but to read python that uses them. You will learn a lot from taking apart existing code and understanding how it works, as opposed to slowly repeating the mistakes others have made, documented and tested before you.

FoiledAgain
May 6, 2007

Eliza posted:

code:
    while (!validate(cur_name)) # Check whether it conforms to whatever you expect of it
        cur_nameraw_input("Player name: ")


What does the ! prefix on validate mean?

vvvv Thanks!

FoiledAgain fucked around with this message at 02:39 on Jan 31, 2012

ufarn
May 30, 2009

FoiledAgain posted:

What does the ! prefix on validate mean?
not; if validates True, you get False.

Thermopyle
Jul 1, 2003

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

tef posted:

twisted I find is more an abstraction around an event loop over an abstraction useful for writing event driven code -- i.e it is more convenient for the twisted maintainers than the users. I find myself more attached to the co-routine style (PEP-342) things which have started to appear (monocle, bluelet and even in twisted (but undocumented, of course)).

Yes, co-routines are where I sometimes end up after deciding Twisted is too magical for me.

It's been awhile since I needed anything co-routiney, but when I did I liked Eventlet.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

tef posted:

twisted I find is more an abstraction around an event loop over an abstraction useful for writing event driven code -- i.e it is more convenient for the twisted maintainers than the users.

There are lots of random things in Twisted. It's a large library with lots of random things. You can make an ssh server really quickly. There's code for an SFTP server, and an IRC server. They have their own authentication framework. It uses zope.interface.

tef posted:

I find myself more attached to the co-routine style (PEP-342) things which have started to appear (monocle, bluelet and even in twisted (but undocumented, of course)).

Once you understand things like Deferreds and the techniques that you can use with those, it becomes a lot easier. If you're having trouble understanding them, it's not you: async programming is confusing. I started but never finished a bunch of tutorials on Deferreds a little while ago: DeferHowTo-Fixup (and its older cousin DeferHowTo-Fixup-1), and DeferHowTo-Rewrite. They're nowhere near perfect, but hopefully they clear up the motivation there. I also use the cooking metaphor somewhere in those documents because it's a pretty excellent metaphor for asynchronous and parallel tasks: preheat the oven, do other things in the mean time, respond when the timer dings, etc.

If you've never done asynchronous programming, go read Eric Lippert's post on it, and then read the introduction to part two where he explains that this is orthogonal to threading. Asynchronity, concurrency, parallelism and threading are all separate, but related things.

Of course, Twisted also has things like monocle, bluelet, etc. It's called inlineCallbacks, and the wonder of it is that it's just a giant magic wrapper around Deferreds. The encapsulation is only to that function - to the rest of the world, it's just another Deferred.



Oh, and in case you need to deal with blocking code (like DBAPI), Twisted has a deferToThread method that will stick that call on its own thread and provide you with a Deferred that you can attach your own callbacks to.

Suspicious Dish fucked around with this message at 15:41 on Jan 31, 2012

NadaTooma
Aug 24, 2004

The good thing is that everyone around you has more critical failures in combat, the bad thing is - so do you!

ufarn posted:

not; if validates True, you get False.

Not to be pedantic, but Python has no "!" operator. He wants the "not" keyword instead.

The Gripper
Sep 14, 2004
i am winner

tef posted:

twisted I find is more an abstraction around an event loop over an abstraction useful for writing event driven code -- i.e it is more convenient for the twisted maintainers than the users. I find myself more attached to the co-routine style (PEP-342) things which have started to appear (monocle, bluelet and even in twisted (but undocumented, of course)).
I checked out Monocle a few weeks back and while it looked great (and actually more suitable than Twisted would be for me) I couldn't figure out how to get it working on any of my machines. Played around with it again today and it turns out the README.md Http example @ their github is just broken, missing a client.connect(host, port) request before client.request(url).

I don't know if that's how it's supposed to work though, since it makes the scheme://host:port explode in HttpClient.request() pointless, as you need to pass a pre-split host and port (and scheme though it defaults to 'http') to connect() anyway (which assigns them to self.host, port, scheme). You can then just use resp = yield client.request("/path/to/doc") rather than resp = yield client.request("http://127.0.0.1/path/to/doc:8088").

Is this right? It might just be that the HTTP module isn't fully fleshed out for all I know.

The Gripper fucked around with this message at 08:39 on Jan 31, 2012

Comrade Gritty
Sep 19, 2011

This Machine Kills Fascists

Comrade Gritty fucked around with this message at 00:45 on May 17, 2014

Adbot
ADBOT LOVES YOU

tef
May 30, 2004

-> some l-system crap ->

The Gripper posted:

I checked out Monocle a few weeks back and while it looked great (and actually more suitable than Twisted would be for me) I couldn't figure out how to get it working on any of my machines.

Is this right? It might just be that the HTTP module isn't fully fleshed out for all I know.

The http module seems to mostly be complete for abstracting around tornado or twisted. From what I saw the monocle http code itself wasn't very complete

  • Locked thread