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
Bodhi Tea
Oct 2, 2006

seconds are secular, moments are mine, self is illusion, music's divine.
What's the best way to completely break out of a nested loop?

Adbot
ADBOT LOVES YOU

bitprophet
Jul 22, 2004
Taco Defender

Bodhi Tea posted:

What's the best way to completely break out of a nested loop?

Raise an exception? v:shobon:v

Boblonious
Jan 14, 2007

I HATE PYTHON IT'S THE SHITTIEST LANGUAGE EVER PHP IS WAY BETTER BECAUSE IT IS MADE FOR THE WEB AND IT USES MYSQL WHICH IS ALSO USED BY GOOGLE AND THATS WHY ITS SO MUCH BETTER THAN PYTHON EVEN HTML IS A BETTER PROGRAMMING LANGUAGE THAN PYTHON

Bodhi Tea posted:

What's the best way to completely break out of a nested loop?

Another option is to put your loops in a function and then return from the function. This doesn't work as well if you need to pass a lot of variables into the function though.

spankweasel
Jan 4, 2006

I'm looking for some good Python questions to ask a potential candidate during an interview. I'm pretty new to being the interviewer, so I'm not real sure what to ask.

The candidate's resume has mention of Python experience, but I need a series of questions that will hopefully tell me how experienced they are.

These questions don't have to be brutally difficult or deal with things like Python internals, but I'd like to get some ideas of how much they know about Python.

tef
May 30, 2004

-> some l-system crap ->

Bodhi Tea posted:

What's the best way to completely break out of a nested loop?

return


for example

code:
def foo(a,b,c):
     ....
     def stuff():
             ..... nested loops
             return a+b+c

     ret = stuff()

     ........

tef
May 30, 2004

-> some l-system crap ->

spankweasel posted:

These questions don't have to be brutally difficult or deal with things like Python internals, but I'd like to get some ideas of how much they know about Python.

what do the inspect, dis, contextmanager libraries do?

name one function in itertools and describe how to implement it (when in doubt, ask them to implement chain)

can you write a flatten function i.e [[1],[[2,[[4]]] -> [1,2,4] - how does it deal with strings

whats the key difference between wsgi in python 2 and 3 - why is this

when might you use threading and when might you use multiprocessing

why is it ",".join(iter) and not iter.join(",")

what do __all__ __main__ __debug__ do

name one data structure in the collections library and implement it (when in doubt ask them to implement an ordered dict

why should you never post to python-dev asking to remove the gil

new style vs old style classes - whats differences roughly

what is a decorator? how does @property work?

what's special about pythons sorting algorithm

what's special about hashing a number

why does 1 is 1 work and why must you never do it

what is id() and why shouldn't you store the result

what's wrong with def foo(a=None,x=[]): x.append(a)

what's wrong with x = [[]]*5

can you tell me any of the output of 'import this'

what might I find in __future__ (for bonus points, braces)

Lurchington
Jan 2, 2003

Forums Dragoon
there's a fair bit of low-level in there, plus the occasional in-joke/point trivia, but good list.

here's what I interviewed on in a previous gig:
What is the GIL? What approaches to be people take to work around this?
What is the WSGI specification? How does mod_python differ from mod_wsgi?
How do closures work in Python and what are their limitations? What additional closure-related functionality will be available with Python 3000?
What XML parsing libraries are available in the python standard library?
How would you add support UTF-8 to an existing Python application? Any gotchas?
What is the difference between an integer and a long in Python? In Python 3?
Why is r"ab\"c" a five character string while r"abc\" is a syntax error?
What error could the following line generate, and how could it be made safe?
formatted = "The value is %s"%some_function()
(assume some_function is guaranteed to exist and not generate an exception on its own)
What attribute must be defined on an object for it to be used in conjunction with the "with" statement?

edit: I almost forgot, ONLY 3 DAYS TO REGISTER AT THE DISCOUNTED RATE FOR PYCON 2011 IN ATLANTA!.
https://www.pycon.com
I'm attending for the first time this year, I'm excited :)

Lurchington fucked around with this message at 22:31 on Jan 14, 2011

Stabby McDamage
Dec 11, 2005

Doctor Rope

Spime Wrangler posted:

I'd try just using pydot with pyparsing, which is what python-graph appears to be built on top of anyways.

The python-graph site says those features require 2.6, but the pydot 0.9.10 docs say it was written in 2.3.4. Even on its own it's pretty drat straightforward. Its what I've been using for making throwaway graphs, as I didn't even know python-graph existed. :v:

This looked perfect, until I see that the module is almost entirely focused on making pictures with GraphViz, and the representation doesn't even track nodes correctly.

code:
>>> g=Graph()
>>> g.add_edge(Edge(Node(1),Node(2)))
>>> g.get_node_list()
[]
:eng99:

It's okay...the Graph implementation I banged out in 5 minutes does what I need.

code:
class Graph(object):
    def __init__(self): self.g = defaultdict(set)
    def add_edge(self,a,b): self.g[a].add(b)
    def remove_edge(self,a,b): self.g[a].remove(b)
    def incoming(self,n): return (x for x in self.g if n in self.g[x])
    
    def nodes(self):
        # i dont track nodes separately, so we traverse the graph and find all nodes 
        # (slow, but im lazy -- if this is a problem, just keep track of nodes in 
        #  a separate set, but that may make remove_edge more expensive)
        return set( self.g.keys() ).union( reduce(set.union, self.g.values(), set()) )
        
    def edges(self):
        for (src,dests) in self.g.items():
            for dest in dests:
                yield (src,dest)

Stabby McDamage fucked around with this message at 23:22 on Jan 14, 2011

Stabby McDamage
Dec 11, 2005

Doctor Rope

tef posted:

why is it ",".join(iter) and not iter.join(",")

what's special about pythons sorting algorithm

what's special about hashing a number

why does 1 is 1 work and why must you never do it

what is id() and why shouldn't you store the result


I thought I knew a fair bit of python, but I think I could learn from having some of the above answered, even if it's just a brief sketch.

quote:

can you tell me any of the output of 'import this'

You don't really rate them on something like this, do you? It's just an easter egg...

good jovi
Dec 11, 2000

Stabby McDamage posted:

You don't really rate them on something like this, do you? It's just an easter egg...

How good a python programmer could they be if they hadn't been using it long enough, or didn't care about the community enough to have seen that before?

Stabby McDamage
Dec 11, 2005

Doctor Rope

zarg posted:

Hi guys.

I'm just getting my feet wet in Python, (taking a first year programming course at my university where we are learning 2.7) and I have a specific application that I ultimately want to have python interacting with. The application is a remote admin program I use at work, (I'm a systems analyst for the government) called RAdmin. My end goal is to have my program initiating a bunch of connections, (about 20) to a group of static IPs using a standard user ID and password.

I know this is pretty ambitious for a beginner, (I have next to no programming experience) so I want to start small and take it slow. I plan to bug my prof with most of my questions, but I dont go back to class for a full week and a few questions are eating away at me :)

My first question is simply how do I go about having python check to see if a specific EXE is running? I figure a good start would simply be checking to see if radmin.exe is running, then telling the user to start it if it is not and re-checking upon input from the user. Or am I going at this all wrong and I need to somehow embed my code within the program itself?

I'm not asking for, nor do I want, you to simply write the code for me. What I'm really looking for is someone to just point me in the right direction so I can learn and understand the concepts on my own. What's the technical term for python interacting with another application in this way? Is there a basic FAQ or tutorial specifically on this subject kicking around? I tried googling several variations on "python interacting with other applications," but I seem to have the wrong keyword or something.

tl;dr: Is there a tutorial for having python check to see if another application is running, or just interacting with other applications in general?

You'll need to figure out how you're going to be interacting with this program.

Is it a Windows GUI? If so, this could be a very tricky task, and one that Python may not be the best tool for.

Is it a web-based interface? If so, Python can work...you'll be using something like httplib or twill or something.

Command-line? That can work very well...you'll be using subprocess and, if it's an interactive shell, maybe pexpect.

However, if it has an actual API for programs to interface with, that will be your best bet. This could be something like an XML/HTTP interface, in which case you'll be using dom and httplib to send/receive XML requests and responses.

As to your current task, there are two ways to go about it. The best one is to try whatever method you're going to eventually use to interact with the app, and see if it succeeds. If not, it may not be running. You can also ask directly: is such-and-such process currently running? This depends on the OS. On Linux/UNIX, I'd use the command-line tool 'ps' to get the list, then search it. On Windows, you'll be doing some library calls...I don't have any experience there. As far as I know, there's no platform-independent module to do this.

EDIT:

Sailor_Spoon posted:

How good a python programmer could they be if they hadn't been using it long enough, or didn't care about the community enough to have seen that before?

I don't want to get into an interviewing argument, but I didn't know what that would output, and I know a decent amount of Python. I'd seen that poem before, but I didn't remember that "import this" produces it.

Let me put it like this: I wouldn't mind if you added bonus points for knowing that bit of trivia, but I wouldn't ding anyone for not knowing it.

A better question might be to show them the "Zen of Python" and the "Zen of Perl" and ask which is which. :v:

EDIT2: Ugh, I just read that Zen of Perl in detail, and memories of how bad Perl can get at large scale came flooding back. That poem is like developer Stockholm Syndrome. "Just because the code looks messy doesn't mean it is bad." :rolleyes:

echinopsis posted:

matplotlib?

I meant the "nodes and edges" kind of graph, not the wavy line kind.

Stabby McDamage fucked around with this message at 23:09 on Jan 14, 2011

good jovi
Dec 11, 2000

Stabby McDamage posted:

A better question might be to show them the "Zen of Python" and the "Zen of Perl" and ask which is which. :v:

haha, I do like that one

good jovi
Dec 11, 2000

zarg posted:

tl;dr: Is there a tutorial for having python check to see if another application is running, or just interacting with other applications in general?

I've never done any windows programming, but WMI looks like something that might do what I think it is that you want.

Though, I'm not actually quite sure what that is. Are you hoping to talk to some service on multiple other machines? Or do you just want to know that radmin.exe is running on your computer? Do you know that RAdmin actually provides some kind of interface for you to talk to?

tef
May 30, 2004

-> some l-system crap ->

Lurchington posted:

plus the occasional in-joke/point trivia

guilty as charged. I like to ask a variety of technical and odd questions to get a feel for things.

knowing bits of trivia is a sign of paying attention to dev chatter/community

Stabby McDamage posted:

I thought I knew a fair bit of python, but I think I could learn from having some of the above answered, even if it's just a brief sketch.

why is it ",".join(iter) and not iter.join(",")

- because we only need one method in string, and not one method in every iterable.

what's special about pythons sorting algorithm
-timsort is magical :3:

what's special about hashing a number

>>> [hash(x) for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


c.f dictnotes in the svn

why does 1 is 1 work and why must you never do it
- numbers stored boxed on heap, but -4 to 255 (approx) are cached

what is id() and why shouldn't you store the result
- id gives you back a magic number that represents a pointer

if you compare the id of two live objects, it is a safe operation
if you store the magic number there is no guarantee the object is still alive
and it is possible to get false positives when bits are recycled.

really, if you need to compare object identity, use 'is'



quote:

You don't really rate them on something like this, do you? It's just an easter egg...

knowing the zen of python is a good sign of someone who understands the nature of python

'explicit is better than implicit' is a good python-ism i'd expect a competent python dev to know.


I've dressed them up and there is a few jokes in there so i'm not 100% serious but I would probably ask these just to see what happens, but i've jokingly asked people how they go about solving tsp :v:

zarg
Mar 19, 2005

We are the Unity 3D community. You will be assimilated. Resistance is futile.

Stabby McDamage posted:

You'll need to figure out how you're going to be interacting with this program.

Is it a Windows GUI? If so, this could be a very tricky task, and one that Python may not be the best tool for.

Is it a web-based interface? If so, Python can work...you'll be using something like httplib or twill or something.

Command-line? That can work very well...you'll be using subprocess and, if it's an interactive shell, maybe pexpect.

However, if it has an actual API for programs to interface with, that will be your best bet. This could be something like an XML/HTTP interface, in which case you'll be using dom and httplib to send/receive XML requests and responses.

As to your current task, there are two ways to go about it. The best one is to try whatever method you're going to eventually use to interact with the app, and see if it succeeds. If not, it may not be running. You can also ask directly: is such-and-such process currently running? This depends on the OS. On Linux/UNIX, I'd use the command-line tool 'ps' to get the list, then search it. On Windows, you'll be doing some library calls...I don't have any experience there. As far as I know, there's no platform-independent module to do this.

We mostly use a windows GUI but it does support some command line switches. I've already written a simple batch file that initiates connections to all the workstations I need to connect to, (read: gets me to the "please enter userid/password" window prior to getting the remote running) so all I really need python to do is something simple like below.

Is a radmin connection window open?
If yes, then put userid xxx and password xxx.
If no, then quit.
Loop until no.

Ideally I'd like to put some sort of escape command just in case something goes wrong, but I can deal with that once I get something up and running in the first place.

Any thoughts on how I would tell python what to look for? Is it even possible? I've already looked around on google and the radmin forums and it does not seem to be possible to include a user ID or password in the command line stuff in my batch file. I'm only keen to use python because it's what we are learning in my course, so I'd like to both practice it and be able to ask my prof questions.

Spime Wrangler
Feb 23, 2003

Because we can.

Stabby McDamage posted:

This looked perfect, until I see that the module is almost entirely focused on making pictures with GraphViz, and the representation doesn't even track nodes correctly.

Oh, i guess i was under the impression making pictures was the idea, probably because I've always used it to visualize existing data structures, and have never run across a package actually designed to represent and operate on the graphs themselves.

I would usually just check for the existence of each node, add if they weren't yet there, and then create the edge. I'm usually working with relatively small graphs (10-50 nodes) so there weren't really any performance issues. FWIW, you can also use pydot.graph_from_edges(list_of_tuples) and it will make the nodes for you.

However I spent some time poking through the networkx docs last night and today and I'm never. going. back.

I swear at least once every month I stumble across some library that offloads a huge chunk of my workload and I gushily fall in love with python all over again.

Now if only there were a simulink equivalent...

Stabby McDamage
Dec 11, 2005

Doctor Rope

zarg posted:

We mostly use a windows GUI but it does support some command line switches. I've already written a simple batch file that initiates connections to all the workstations I need to connect to, (read: gets me to the "please enter userid/password" window prior to getting the remote running) so all I really need python to do is something simple like below.

Is a radmin connection window open?
If yes, then put userid xxx and password xxx.
If no, then quit.
Loop until no.

Ideally I'd like to put some sort of escape command just in case something goes wrong, but I can deal with that once I get something up and running in the first place.

Any thoughts on how I would tell python what to look for? Is it even possible? I've already looked around on google and the radmin forums and it does not seem to be possible to include a user ID or password in the command line stuff in my batch file. I'm only keen to use python because it's what we are learning in my course, so I'd like to both practice it and be able to ask my prof questions.

In that case, Python may not be your best bet. If there is really and truly no way to use this app other than the GUI, and you simply have to automate this program, then you'd be looking at some kind of GUI-driving macro tool, maybe AutoIt.

Looking at what radmin does, I'm not sure what you need to automate with it. It looks like just another commercial VNC/RDP knockoff, right? If the goal is to automatically perform tasks on a number of remote computers, people generally use Active Directory policies or some other programmatic means of control. Getting a remote GUI and simulating mouse/keyboard events is a pretty painful alternative.

EDIT: Can you give me a full, concrete task you'd like to automate?

Spime Wrangler posted:

Oh, i guess i was under the impression making pictures was the idea, probably because I've always used it to visualize existing data structures, and have never run across a package actually designed to represent and operate on the graphs themselves.

I would usually just check for the existence of each node, add if they weren't yet there, and then create the edge. I'm usually working with relatively small graphs (10-50 nodes) so there weren't really any performance issues. FWIW, you can also use pydot.graph_from_edges(list_of_tuples) and it will make the nodes for you.

However I spent some time poking through the networkx docs last night and today and I'm never. going. back.

I swear at least once every month I stumble across some library that offloads a huge chunk of my workload and I gushily fall in love with python all over again.

Now if only there were a simulink equivalent...

I'm working with compiler call graphs, and visualizing is an intermediate step, but I much prefer dumping it out in Trivial Graph Format to yEd, where I can use multiple layout algorithms and analysis tools interactively. That's just so I can understand it...the main purpose of the graph is program-driven transformations. (This is a security research project at the compiler level.)

Stabby McDamage fucked around with this message at 19:14 on Jan 15, 2011

zarg
Mar 19, 2005

We are the Unity 3D community. You will be assimilated. Resistance is futile.

Stabby McDamage posted:

In that case, Python may not be your best bet. If there is really and truly no way to use this app other than the GUI, and you simply have to automate this program, then you'd be looking at some kind of GUI-driving macro tool, maybe AutoIt.

Looking at what radmin does, I'm not sure what you need to automate with it. It looks like just another commercial VNC/RDP knockoff, right? If the goal is to automatically perform tasks on a number of remote computers, people generally use Active Directory policies or some other programmatic means of control. Getting a remote GUI and simulating mouse/keyboard events is a pretty painful alternative.

EDIT: Can you give me a full, concrete task you'd like to automate?

There is no API for RAdmin, but it does support command line switches like /connect, which launches the window that prompts users for their info.

My goal right now is simply to launch that user info window, then fill in the user information automatically to complete the connection. I have to launch the same 20 connections multiple times daily at work, so I just want to be able to automate that. I'm checking to see if a certain process has been started on those machines, but writing code to automate that step is way, way beyond me. For now I just want to open the windows automatically so save me starting the same 20 connections over and over.

Thermopyle
Jul 1, 2003

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

Stabby McDamage posted:

In that case, Python may not be your best bet. If there is really and truly no way to use this app other than the GUI, and you simply have to automate this program, then you'd be looking at some kind of GUI-driving macro tool, maybe AutoIt.

He could use AutoIt's COM bindings in python. I gave a little example of how to do that on this StackOverflow answer.

Yakattak
Dec 17, 2009

I am Grumpypuss
>:3

Python importing is starting to make me want to commit suicide.

I have the following stacktrace when I try to import ModuleA:

code:
Traceback (most recent call last):                                                          
  File "menu.py", line 9, in <module>                                                       
    from tmserver import Module1                                                          
  File "~/tmserver/Module1.py", line 10, in <module>                                                                           
    from tmserver.PackageA import ModuleA                                             
  File "~/tmserver/Package1/ModuleA.py", line 8, in <module>                                                               
    from tmserver.Package2 import Module2                                               
  File "~/tmserver/Package2/Module2.py", line 15, in <module>                                                                
    from tmserver.Package3 import Module3                                                      
  File "~/tmserver/Package3/Module3.py", line 5, in <module>                                                                        
    from tmserver.PackageA import ModuleA                                            
ImportError: cannot import name ModuleA                                               
Is this because it's importing ModuleA again/recursively?

Yakattak fucked around with this message at 19:24 on Jan 16, 2011

Lurchington
Jan 2, 2003

Forums Dragoon

Yakattak posted:

Python importing is starting to make me want to commit suicide.

I have the following stacktrace when I try to import ModuleA:

code:
Traceback (most recent call last):                                                          
  File "menu.py", line 9, in <module>                                                       
    from tmserver import Module1                                                          
  File "~/tmserver/Module1.py", line 10, in <module>                                                                           
    from tmserver.Package1 import ModuleA                                             
  File "~/tmserver/Package1/ModuleA.py", line 8, in <module>                                                               
    from tmserver.Package2 import Module2                                               
  File "~/tmserver/Package2/Module2.py", line 15, in <module>                                                                
    from tmserver.Package3 import Module3                                                      
  File "~/tmserver/Package3/Module3.py", line 5, in <module>                                                                        
    from tmserver.PackageA import ModuleA                                            
ImportError: cannot import name ModuleA                                               
Is this because it's importing ModuleA again/recursively?

probably, stuff like that happens to me. I have some global stuff in A, and I define the global logger in B using some of that stuff, and I want access to the logger B. :v: It's a mess, it makes sense, but eh I wish it was slightly different

Yakattak
Dec 17, 2009

I am Grumpypuss
>:3

Lurchington posted:

probably, stuff like that happens to me. I have some global stuff in A, and I define the global logger in B using some of that stuff, and I want access to the logger B. :v: It's a mess, it makes sense, but eh I wish it was slightly different

What did you end up doing to remedy it?

tef
May 30, 2004

-> some l-system crap ->
not writing circular dependencies in import statements :v:

this is a mixture of putting things together and apart in files

break the dependencies by eliminating them or clearer boundaries with newer modules.

you have bits in A and B that depend on each other, so you put them in C and A,B import C
or you put all the co-dependent bits in A and so only B imports A

can't give exacts without source though.

Sneftel
Jan 28, 2009
Incidentally, that's another great reason not to use from X import Y. You can have two modules import each other, and use each other's functions in their own functions, as long as you defer the lookup until after initialization is done.

Example:
code:
##### a.py #####

import b

def foo(x):
    if x > 0:
        print x
        b.bar(x-1)



##### b.py #####

import a

def bar(x):
    if x > 0:
        print x
        a.foo(x-1)
Works fine, since both modules can import without looking in each other's namespaces. Change it to from a import foo and from b import bar, and you'll get a rather familiar traceback.

Sneftel fucked around with this message at 20:10 on Jan 16, 2011

b0lt
Apr 29, 2005

Sneftel posted:

Incidentally, that's another great reason not to use from X import Y. You can have two modules import each other, and use each other's functions in their own functions, as long as you defer the lookup until after initialization is done.

Example:
code:
##### a.py #####

import b

def foo(x):
    if x > 0:
        print x
        b.bar(x-1)



##### b.py #####

import a

def bar(x):
    if x > 0:
        print x
        a.foo(x-1)
Works fine, since both modules can import without looking in each other's namespaces. Change it to from a import foo and from b import bar, and you'll get a rather familiar traceback.

That actually still fails:

code:
##### a.py #####

import b

def foo(x):
    if x > 0:
        print x
        b.bar(x-1)



##### b.py #####

import a

a.foo(1)

def bar(x):
    if x > 0:
        print x
        a.foo(x-1)
will give you the same problem

Yakattak
Dec 17, 2009

I am Grumpypuss
>:3

tef posted:

not writing circular dependencies in import statements :v:

this is a mixture of putting things together and apart in files

break the dependencies by eliminating them or clearer boundaries with newer modules.

you have bits in A and B that depend on each other, so you put them in C and A,B import C
or you put all the co-dependent bits in A and so only B imports A

can't give exacts without source though.

The way I have my code setup is that ModuleA is a logger, Module2 is a class that ModuleA uses to email a specified user with the error message made by ModuleA. Module3 gives Module2 the email of the specified user. Since Module2 and 3 both require logging, ModuleA is required to be imported. I imagine if I had diagrammed this up it'd be a clusterfuck of circular dependencies.

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"

Yakattak posted:

The way I have my code setup is that ModuleA is a logger, Module2 is a class that ModuleA uses to email a specified user with the error message made by ModuleA. Module3 gives Module2 the email of the specified user. Since Module2 and 3 both require logging, ModuleA is required to be imported. I imagine if I had diagrammed this up it'd be a clusterfuck of circular dependencies.

If you can, move one of the imports into a procedure -- that should break the loop.

Yakattak
Dec 17, 2009

I am Grumpypuss
>:3

Janin posted:

If you can, move one of the imports into a procedure -- that should break the loop.

A procedure being..? I'm a scrub at Python.

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"

Yakattak posted:

A procedure being..? I'm a scrub at Python.

instead of

code:
import foo

def myproc():
  foo.dosomething()
use

code:
def myproc():
  import foo
  foo.dosomething()

Yakattak
Dec 17, 2009

I am Grumpypuss
>:3

Janin posted:

instead of

code:
import foo

def myproc():
  foo.dosomething()
use

code:
def myproc():
  import foo
  foo.dosomething()

:aaa:

I see, that makes sense. Thanks!

tef
May 30, 2004

-> some l-system crap ->

Yakattak posted:

The way I have my code setup is that ModuleA is a logger, Module2 is a class that ModuleA uses to email a specified user with the error message made by ModuleA. Module3 gives Module2 the email of the specified user. Since Module2 and 3 both require logging, ModuleA is required to be imported. I imagine if I had diagrammed this up it'd be a clusterfuck of circular dependencies.

it is always logging code :v:

especially if you have to try logging an error in the bit that generates emails, as if that bit errors out what do you do?

i would avoid putting imports into function calls, it buries errors, but gently caress it, it would mostly work here, that is until you try and emit a message while a module is loading.

in logging
code:
# no imports
email_handler = None

def set_email_handler(n):
     email_handler = n
     return n



def log_shit(..):
    if email_handler....
code:
import logger

@logger.set_email_handler
def blah blah():
    blah blah

Sneftel
Jan 28, 2009

b0lt posted:

That actually still fails:

code:
...
##### b.py #####

import a

a.foo(1)
Of course it fails, you're running that function during import. import a and call a.foo from main.py instead and it'll work fine.

Evil Robot
May 20, 2001
Universally hated.
Grimey Drawer
I have JSON strings that look like: '{iv:"AeoaE1eWTylwz7sTP8NSUg",salt:"lan13206tsA",ct:"Ued7w0WQZm8cRsufAkWj"}'. How do I get the Python JSON module to accept these JSON objects that don't have quotes around the keys?

Haystack
Jan 23, 2005





Evil Robot posted:

I have JSON strings that look like: '{iv:"AeoaE1eWTylwz7sTP8NSUg",salt:"lan13206tsA",ct:"Ued7w0WQZm8cRsufAkWj"}'. How do I get the Python JSON module to accept these JSON objects that don't have quotes around the keys?

That's not valid JSON, and most parsers won't take it. Valid JSON requires the key to be a string literal or a number.

A quick bit of googling says that demjson.py will accept your form of invalid JSON. Haven't tried it myself, but it's worth a shot, I suppose.

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"

Evil Robot posted:

I have JSON strings that look like: '{iv:"AeoaE1eWTylwz7sTP8NSUg",salt:"lan13206tsA",ct:"Ued7w0WQZm8cRsufAkWj"}'. How do I get the Python JSON module to accept these JSON objects that don't have quotes around the keys?
Have you considered using real JSON instead of whatever that is?

zarg
Mar 19, 2005

We are the Unity 3D community. You will be assimilated. Resistance is futile.

zarg posted:

My goal right now is simply to launch that user info window, then fill in the user information automatically to complete the connection. I have to launch the same 20 connections multiple times daily at work, so I just want to be able to automate that. I'm checking to see if a certain process has been started on those machines, but writing code to automate that step is way, way beyond me. For now I just want to open the windows automatically so save me starting the same 20 connections over and over.

I'm getting close a solution here. I've got some issues to resolve still, but I'm getting promising results. I've veered off of the python path because I think you guys are right and it's not the best tool, but since you have all been very helpful I figured I'd keep posting here to share my progress so far :)

Step 1:
.bat file launches 20 connections, bringing up a window requesting user information.

Step 2: Execute a macro in macroexpress (the only macro app currently OK'ed for use here) which is simply "userid<TAB>password<ENTER>" to autocomplete the login. This macro is password protected for use and edit with the password it is entering, so effectivly it asks the user for the information once then auto-completes subsequent entries, if I can get the macro to repeat for all open connection windows correctly.

Problems:

Step 1:
My .bat only launches one connection window at a time. It opens the window, lets me do what I want, then when I close it the next window opens. Instead I want every connection command to launch its own window. I'm not sure how to overcome this but I'm working on it. Suggestions would be fantastic. Linking a bunch of 1 line bats together is less than ideal, as I'm actually going to end up making 10 .bat files with 20 connections each, so that would total 200 linked .bat files :(

Step 2:
Macro applies to the current window only. There are some nice repeat functions, (until is one of them) in the macro app I'm using, (Macro Express) but I'm not sure how to force it to repeat for a specific type of window until that type is not found. It can identify windows, but it actually seems to think that each different IP is a unique window "type," so I'm not sure how to make it look for ANY radmin connection window just yet.

zarg fucked around with this message at 22:24 on Jan 17, 2011

Evil Robot
May 20, 2001
Universally hated.
Grimey Drawer

Janin posted:

Have you considered using real JSON instead of whatever that is?

Yeah, some other library is giving me back this crap. Did some regexps to put in the appropriate quotes :/.

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

Evil Robot posted:

Yeah, some other library is giving me back this crap. Did some regexps to put in the appropriate quotes :/.

I had a similar problem, since the output ended up being correct python, i just used ast.literal_eval.

Carthag Tuek
Oct 15, 2005

Tider skal komme,
tider skal henrulle,
slægt skal følge slægters gang



I'm having an issue with os.walk() and unicode paths.

There's a directory that looks like this:
code:
/path/to/dir/a
/path/to/dir/b
/path/to/dir/b/ünicøde.txt
u'/path/to/dir' is stored (as a unicode string) in an object's watchedFolder property, and at a certain point, the following code executes and fails:

code:
for root, dirs, files in os.walk(self.watchedFolder):
	# do stuff
I get this backtrace:

code:
  File "model.py", line 166, in getReadyWatchedFiles
    for root, dirs, files in os.walk(self.watchedFolder):
  File "/usr/lib/python2.5/os.py", line 304, in walk
    for x in walk(path, topdown, onerror):
  File "/usr/lib/python2.5/os.py", line 304, in walk
    for x in walk(path, topdown, onerror):
  File "/usr/lib/python2.5/os.py", line 294, in walk
    if isdir(join(top, name)):
  File "/usr/lib/python2.5/posixpath.py", line 65, in join
    path += '/' + b
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf8 in position 2: ordinal not in range(128)
I was under the impression that passing unicode paths to os.walk & others should yield unicode responses? But as you can see it doesn't even get that far, it just dies.

Running on Debian lenny with locale is en/utf8

Adbot
ADBOT LOVES YOU

tef
May 30, 2004

-> some l-system crap ->
file paths aren't in unicode, they're bytestrings on most platforms :worms:


there was some hoo-haa about it around python 3 and the file-io stuff.

I think you'll need to encode the unicode before using it

  • Locked thread