How to call and execute C code in Python?

David Shi davidgshi at yahoo.co.uk
Sun May 13 09:25:54 EDT 2012


Can anyone tell me how to call and exectute C code in Python?

Regards.

David



________________________________
 From: "python-list-request at python.org" <python-list-request at python.org>
To: python-list at python.org 
Sent: Friday, 11 May 2012, 5:35
Subject: Python-list Digest, Vol 104, Issue 57
 
----- Forwarded Message -----

Send Python-list mailing list submissions to
    python-list at python.org

To subscribe or unsubscribe via the World Wide Web, visit
    http://mail.python.org/mailman/listinfo/python-list
or, via email, send a message with subject or body 'help' to
    python-list-request at python.org

You can reach the person managing the list at
    python-list-owner at python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Python-list digest..."

Today's Topics:

   1. Looking for video/slides from PyCon 2011... (Monte Milanuk)
   2. Re: Dealing with the __str__ method in classes with lots of
      attributes (Cameron Simpson)
   3. RE: Open Source: you're doing it wrong - the Pyjamas hijack
      (Adrian Hunt)
   4. RE: Creating a Windows installer for Python + a set of
      dependencies (Adrian Hunt)
   5. Re: Open Source: you're doing it wrong - the Pyjamas hijack
      (Chris Angelico)
   6. Re: Retrieving result from embedded execution (Chris Angelico)
   7. Finding the line number of an 'else' statement via ast
      (Michael Rene Armida)
...specifically the two lectures on creating GUI applications with Python + QT

http://us.pycon.org/2011/schedule/presentations/207/

Various searches on the 'Net don't seem to be turning up much... kinda curious as to why?

Anyone here know?

TIA,

Monte


On 10May2012 15:33, Andreas Tawn <andreas.tawn at ubisoft.com> wrote:
| Say I've got a class...
| 
| class test(object):
|     def __init__(self):
|         self.foo = 1
|         self.bar = 2
|         self.baz = 3
| 
| I can say...
| 
| def __str__(self):
|    return "foo: {0}\nbar: {1}\nbaz: {2}".format(self.foo, self.bar, self.baz)
| 
| and everything's simple and clean and I can vary the formatting if I need to.
| 
| This gets ugly when the class has a lot of attributes because the string construction gets very long.

This issue bit me once too often a few months ago, and now I have a
class called "O" from which I often subclass instead of from "object".
Its main purpose is a friendly __str__ method, though it also has a
friendly __init__.

Code:

    class O(object):
      ''' A bare object subclass to allow storing arbitrary attributes.
          It also has a nicer default str() action, and an aggressive repr().
      '''

      def __init__(self, **kw):
        ''' Initialise this O.
            Fill in attributes from any keyword arguments if supplied.
            This call can be omitted in subclasses if desired.
        '''
        for k in kw:
          setattr(self, k, kw[k])

      def __str__(self):
        return ( "<%s %s>"
                 % ( self.__class__.__name__,
                     ",".join([ "%s=%s" % (attr, getattr(self, attr))
                                for attr in sorted(dir(self)) if attr[0].isalpha()
                              ])
                   )
               )

So I have some code thus:

  from cs.misc import O
  ......
  class FilterModes(O):
    def __init__(self, **kw):
        # special case one parameter
        self._maildb_path = kw.pop('maildb_path')
        self._maildb_lock = allocate_lock()
        O.__init__(self, **kw)
  ......
  filter_modes = FilterModes(justone=justone,
                             delay=delay,
                             no_remove=no_remove,
                             no_save=no_save,
                             maildb_path=os.environ['MAILDB'],
                             maildir_cache={})


This removes a lot of guff from some common procedures.

Hope this helps,
-- 
Cameron Simpson <cs at zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

There's a fine line between pathos and pathetic.
        - David Stivers stiv at stat.rice.edu DoD #857


 
lol, Cheers Chris.

Just so you know, I care about what and how I write... I almost always run my emails though a word-processor before sending. And, that has paid off for me: thanks to MS Word, MS Works and Open Office, I have better understanding of "correct" punctuation use (if not spelling and grammar) than most school leavers!!!

PS. It hasn't gone a miss that you are one of the core python-list responders (and I bet this goes for most of the python-list users): your responses, time and knowledge is appreciated... Thank you.


> Date: Fri, 11 May 2012 09:57:49 +1000
> Subject: Re: Open Source: you're doing it wrong - the Pyjamas hijack
> From: rosuav at gmail.com
> To: python-list at python.org
> 
> On Fri, May 11, 2012 at 9:36 AM, Adrian Hunt <cyborgv2 at hotmail.com> wrote:
> > All I did was to answer a mail sent to me by Ian Kelly (who I don't konw nor
> > have ever had any prior contact with) about releasing code under a
> > license... And, what I said stands: once anyone releases code, they are
> > bound by the license they released it under as much as anyone else that may
> > use it and cannot then withdraw that code from the domain they released it
> > to (except by maybe creating a new and different version.)
> 
> And that's absolutely correct. Open source licenses are deliberately
> worded to guarantee rights in perpetuity, so there's no way to
> withdraw it or change the license (though of course a copyright owner
> can release the same code under an additional license).
> 
> > Being dyslexic, my message (and this one) may not be worded in the best way
> > but that is no reason to start on me!
> 
> Your message is fine. Believe you me, I'd much rather read a message
> posted by a non-native English speaker, or a dyslexic person, or
> someone who has a clinical aversion to the letter 'q', than someone
> who's simply sloppy and doesn't care about their language at all.
> 
> Chris Angelico
> -- 
> http://mail.python.org/mailman/listinfo/python-list

 
Hi there,

I've use NSIS for quite a few projects... NSIS will do it with ease. You write a script that gets "compiled" into a install exe and the scripting language is not too hard to learn. You can do it in several different ways:

1. You can include the Python installer as a file compressed into your installer (that is decompressed to a temp directory before being run.)
2. The Python installer could be a included along side you installer and run as needed
3. You can specify a URL to the Python install to be downloaded and installed (again using a temp directory.)

You can even use a mix... If an internet connection is available download it, if not fall back to one of the other methods. If you can come up with yet another method, it wouldn't be simple to write a script to handle it.  If you really need to you can write a dynamic link library that the final NSIS installer will make calls to.

If you need any more help on this subject, email me directly... Although I try to keep an eye on python-list, I can't guarantee a quick reply.




> Date: Thu, 10 May 2012 16:26:25 +0200
> Subject: Creating a Windows installer for Python + a set of dependencies
> From: g.rodola at gmail.com
> To: python-list at python.org
> 
> Hi all,
> I need to create an installer for Windows which should be able to
> install a specific version of the Python interpreter (2.7) plus a set
> a dependencies such as ipython, numpy, pandas, etc.
> Basically this is the same thing Active State did for their Active
> Python distribution: a single bundle including interpreter + deps.
> Not being a Windows user I'm not sure where to start with this except
> maybe looking into NSIS (could that be of any help?).
> 
> Thanks in advance,
> 
> --- Giampaolo
> http://code.google.com/p/pyftpdlib/
> http://code.google.com/p/psutil/
> http://code.google.com/p/pysendfile/
> -- 
> http://mail.python.org/mailman/listinfo/python-list
On Fri, May 11, 2012 at 10:21 AM, Adrian Hunt <cyborgv2 at hotmail.com> wrote:
> lol, Cheers Chris.
>
> Just so you know, I care about what and how I write... I almost always run
> my emails though a word-processor before sending. And, that has paid off for
> me: thanks to MS Word, MS Works and Open Office, I have better understanding
> of "correct" punctuation use (if not spelling and grammar) than most school
> leavers!!!

Absolutely. Taking care puts you miles ahead of the average
(unfortunately for the average). I was home educated, and taught to
value correctness, so I tend to speak and write more carefully than
most do (people say I sound British for some reason - my accent
doesn't sound Australian). That's why I tend to do a lot (note, not
"alot", though the cute drawings are fun) of copyediting.

> PS. It hasn't gone a miss that you are one of the core python-list
> responders (and I bet this goes for most of the python-list users): your
> responses, time and knowledge is appreciated... Thank you.

Thanks! I'm just a guy who types fast, mainly; but I've been coding
for about twenty years, and I'm always happy to help people. But this
list is more for me to learn than for me to share. I've learned no end
of things from these threads - it's awesome!

ChrisA

On Wed, May 9, 2012 at 5:07 AM, F L <mephisto_9000 at hotmail.com> wrote:
> Hello everyone,
>
> We are trying to implement our own interactive interpreter in our
> application
> using an embedded Python interpreter.
>
> I was wondering what would be the best way to retreive as text the result of
> executing Python code. The text must be exactly the same as it would be in
> the
> standalone interpreter.

Greetings!

The standalone interpreter - I assume you mean the interactive prompt?
It has slightly different handling of things (for instance, naked
expressions being written to standard output) from the more "usual"
invocation of the interpreter.

For your embedded Python, probably the easiest thing to do is to not
try to use interactive mode, but script mode:

PyObject* PyRun_String(const char *str, int start, PyObject *globals,
PyObject *locals)

Pass it a string of Python code and a dictionary to use for globals
and locals (they can be the same dict). Then when that finishes,
retrieve from that dictionary some predetermined name (eg "Output").
The Python code then needs simply to assign to Output and all will
work.

Another way to do it is to call a function inside the Python code, and
retrieve its return value.

> We are using python 2.7.
>
> Any suggestions?

Unless you have particular need to stick to the 2.x branch, I would
suggest moving to 3.3; many things are easier (especially Unicode).
But both work.

> Also, I'm new to mailling lists, what is the proper way to reply to someone?
> Should I
> reply directly to someone's email adress or is there a way to answer trough
> the server.

The usual convention is to reply on-list, unless it's particularly
private. Many mail clients will handle this conveniently; otherwise,
just manually replace the To address with the list address. As long as
you use reply (rather than starting a fresh email), all posts will be
correctly threaded both on the list and on the synchronized newsgroup
(comp.lang.python).

Chris Angelico

Given this source:

def do_something(val):
    if val:
        return 'a'
    else:
        return 'b'

How do I get the line number of the "else:" line, using the ast
module?  The grammar only includes the 'orelse' list:

    If(expr test, stmt* body, stmt* orelse)

...but 'orelse' is the list of statements under the 'else' token, not
a node representing the token itself.

I have a suspicion that this isn't possible, and shouldn't be, and the
giveaway word above was "token."  Because the tokens themselves aren't
part of the abstract syntax tree.

Here's an interactive session showing me poking around the If node:

>>> import ast
>>> tree = ast.parse('''
... if True:
...     pass
... else:
...     pass
... ''')
>>> tree.body[0].orelse
[<_ast.Pass object at 0x7f1301319390>]
>>> tree.body[0]._fields
('test', 'body', 'orelse')
>>> for i in ast.iter_child_nodes(tree.body[0]):
...     print i.__class__.__name__
...
Name
Pass
Pass


Is my suspicion correct?  Or is there a way to get the line number of
that 'else:'?


-- 
http://mail.python.org/mailman/listinfo/python-list
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120513/ebefba55/attachment.html>


More information about the Python-list mailing list