install on host not connected to the internet and no local proxy

2017-11-02 Thread Noah

Hi,

I am trying to install a python package with about 80 dependencies on a 
server that is not connected to the internet and has no local proxy.  I 
can ssh to it via VPN.


I was able to find python bundle and download the tarballs for all the 
main python package and all the tarballs for the subsequent 
dependencies.They reside in the same directory on the isolated server.


Does anybody have some recommendations on how to install the main 
package and that process triggers the installation of all the 
dependencies from their corresponding tar.gz file?  I cant seem to 
figure out how to do that easily with pip.


Cheers

--
https://mail.python.org/mailman/listinfo/python-list


Python and ssh for remote login

2016-10-05 Thread Noah
Hello folk,

I would like to use a python script to ssh into a server using a username
and password and perhaps ass port.

Any ideas on how to script that.

Thanks

Noah
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python and ssh for remote login

2016-10-05 Thread Noah
Hi Rob

Thank you for your email.

I am guessing that is some module. Ok i will pip it and see how it goes.

Noah

On 5 Oct 2016 21:32, "Rob Gaddi"  wrote:

> Noah wrote:
>
> > Hello folk,
> >
> > I would like to use a python script to ssh into a server using a username
> > and password and perhaps ass port.
> >
> > Any ideas on how to script that.
> >
> > Thanks
> >
> > Noah
>
> paramiko
>
> --
> Rob Gaddi, Highland Technology -- www.highlandtechnology.com
> Email address domain is currently out of order.  See above to fix.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python and ssh for remote login

2016-10-05 Thread Noah
On 5 Oct 2016 22:02, "Ethan Furman"  wrote:
>
> On 10/05/2016 10:46 AM, Noah wrote:
>
>> I would like to use a python script to ssh into a server using a username
>> and password [...]
>
>
> I've written a module called scription to help with scripts; it supports
giving passwords to programs like ssh.
>

Hi Ethan and for writting this script.

> Here's an example from one of my utility scripts:
>
> -- 8< ---
> #!/usr/local/bin/python
>
> from getpass import getpass
> from antipathy import Path
> from scription import Command, Execute, Main, OPTION, REQUIRED
>
> ...
>
> @Command(
> repo=('repository to pull [default: all]', OPTION),
> path=('base path to search', OPTION, 'p', Path),
> )
> def pull(repo, *path):
> '''
> retrieve remote change sets
> '''
> password = getpass('[mercurial] password: ')
> target = repo
> for repo in workhorse(*path):
> if target and repo.filename != target:
> continue
> history = Execute(('hg', 'pull'), cwd=repo, password=password,
pty=True)
>
> -- 8< 
>
> and in use:
>
> ==
>
> $ hgc --help
> Available commands/options in hgc
>incoming  displays changesets in remote repo not present locally
>list  displays all repos
>log-date  displays all log entries for matching date
>outgoing  displays changesets in remote repo not present locally
>parentdisplays parent of active branch
>pull  retrieve remote change sets
>push  send local changesets to remote repo
>statusdisplay status for each repo
>updateupdate active files to latest version
>
> $ hgc pull
> [mercurial] password:
>
> ...
> ===
>
> It's available via pip.  Feedback welcome.  :)
>

I will pip it too and try it out and give some feedback based on my use
case.

Thanks a lot.

> --
> ~Ethan~
> --

Noah
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: BeautifulSoup help !!

2016-10-06 Thread Noah
+1 at Steve

On 6 Oct 2016 19:17, "Steve D'Aprano"  wrote:

> On Fri, 7 Oct 2016 02:30 am, alister wrote:
>
> > On Thu, 06 Oct 2016 08:22:05 -0700, desolate.soul.me wrote:
> >
> >> So I've just started up with python and an assignment was given to me by
> >> a company as an recruitment task.
> >>
> > so by your own admission you have just started with python yet you
> > consider your self suitable for employment?
>
> What's your problem Alister? Do you think that junior devs aren't allowed
> to
> ask for help?
>
> Desolate.Soul.Me has either applied for a job, and their interview test
> is "do this task using Python", or he's been accepted in a new job, and the
> same applies.
>
> Whether it's a learning exercise, a test of skill + initiative, or actual
> work given to a junior developer, Desolate.Soul.Me is perfectly entitled
> to
> ask for help.
>
> This isn't some artificially constrained academic homework, with stupidly
> strict and hypocritical rules about so-called "plagiarism". This is the
> real world where you take all the help you can get and you shouldn't feel
> ashamed for asking for help. ESPECIALLY in the open source world, including
> Python, where one of the community values is to share expertise.
>
> My own employer has hired plenty of junior developers and given them
> relatively minor tasks to do as a learning exercise. We're not going to
> trust a junior developer with a critical piece of code, but we might say:
>
> "Scrape this website. Use Python. Here's the Python For Beginners
> book. Here's the Python documentation, and a few more forums where
> you can ask for help. If you get stuck, and aren't getting useful
> answers from the forums, you can ask Lisa. But not today, as she's
> busy doing a critical release and can't be disturbed."
>
>
> P.S. Desolate.Soul.Me, you might be taken a bit more seriously if you
> give a
> name, or at least a moniker or nick-name which is easier for others to
> refer to you by. It doesn't have to be your birthname, or legal name. What
> do your friends and workmates call you?
>
>
> I don't know Beautiful Soup, so I'm afraid I can't help.
>
>
>
> --
> Steve
> “Cheer up,” they said, “things could be worse.” So I cheered up, and sure
> enough, things got worse.
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python and ssh for remote login

2016-10-06 Thread Noah
On 6 Oct 2016 04:56, "Michael Torrie"  wrote:
>
> On 10/05/2016 11:46 AM, Noah wrote:
> > Hello folk,
> >
> > I would like to use a python script to ssh into a server using a
username
> > and password and perhaps ass port.
> >
> > Any ideas on how to script that.
>
> If paramiko doesn't fit your needs, traditionally this sort of work was
> done with the pexpect module for drying a TTY. There is a submodule of
> pexpect called pxssh for automating things.
>

Hi Micheal

Thank youn for your suggestion. I played around with paramiko today and the
results are owesome.

> http://pexpect.readthedocs.io/en/stable/api/pxssh.html
>
> Note that pexpect uses your normal ssh binary.  Paramiko is a complete
> implementation of the ssh protocol in python.  Both modules are useful
> and fill certain needs.

So i  am going to also try pexpect and everything pexpect and i will let
you know.

Thank you so much

Noah
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New PyPI launched, legacy PyPI shutting down April 30

2018-04-18 Thread Noah
Awesome

On Mon, Apr 16, 2018 at 8:21 PM, Laura Hampton 
wrote:

> New PyPI launched, legacy PyPI shutting down April 30[1]
>
> Starting today, the canonical Python Package Index is at https://pypi.org
> and uses the new Warehouse codebase.  We announced the https://pypi.org
> beta on March 26 and your feedback and test usage have helped us get it
> production-ready.
>
> Monday April 16 (2018-04-16): We launched the new PyPI, redirecting
> browser traffic and API calls (including "pip install") from
> pypi.python.org to the new site. The old codebase is still available at
> https://legacy.pypi.org for now.
>
> Monday April 30 (2018-04-30): We plan to shut down legacy PyPI
> https://legacy.pypi.org . The address pypi.python.org will continue to
> redirect to Warehouse.
>
> For more details, see our roadmap: https://wiki.python.org/psf/
> WarehouseRoadmap
>
> If your site/service links to or uses pypi.python.org, you should start
> using pypi.org instead: https://warehouse.readthedocs.
> io/api-reference/integration-guide/#migrating-to-the-new-pypi
>
> Thank you.
>
> [1] https://blog.python.org/2018/04/new-pypi-launched-legacy-
> pypi-shutting.html
>
>   Laura Hampton
>   laura at laura-hampton dot com
> --
> https://mail.python.org/mailman/listinfo/python-announce-list
>
> Support the Python Software Foundation:
> http://www.python.org/psf/donations/
>



-- 
*./noah*
-- 
https://mail.python.org/mailman/listinfo/python-list


multiprocessing not quite working

2016-05-24 Thread Noah


Hi,

I am using this example: 
http://spartanideas.msu.edu/2014/06/20/an-introduction-to-parallel-programming-using-pythons-multiprocessing-module/


I am sending and receiving communication from the worker processes.

Two issues. the join is only getting to the process and waiting.
When I comment out the .join() process the output.get() appends the 
previous process and therefore the returned output keeps getting longer 
and longer after each process returns its output.


hostnames is an array of hostnames.

here is my code from main():

# Define an output queue
output = mp.Queue()

# Setup a list of processes that we want to run
processes = [mp.Process(target=worker, args=(hostnames[x], output)) 
for x in range(len(hostnames))]


# Run processes
for p in processes:
print "start: {}".format(p)
p.start()

time.sleep(6)
print "processes: {}".format(processes)

# Exit the completed processes
'''for p in processes:
print "join: {}".format(p)
p.join()'''

print "got here"
# Get process results from the output queue
# results = [output.get() for p in processes]

io = StringIO()
count = 0
for p in processes:
found_output = output.get()
print "returned {}".format(p)
io.write (found_output)
zipArchive.writestr(hostnames[count] + "." + 
content['sitename'] + '.config.txt', io.getvalue())

count = count + 1
io.close()


def worker(hostname, output):
.
.
.
output.put(template_output)


Cheers

--
https://mail.python.org/mailman/listinfo/python-list


python requests get from API and post to another API and remote u'

2019-08-20 Thread Noah

Hi,

I am trying to migrate information and data between two systems using 
their corresponding APIs. I am using python requests.


I place a get request and the response from the API is "{'id': 32, 
'description': u'Firewall Outside', 'address': u'10.10.10.230/30'}"


I then take that information and attempt post it to the other API.  The 
data is not accepted and the result is an HTTP 400 code.


I tried posting with postman and still rejected.

I can post to the second API if I change the data to look like this: 
{"id": 32, "description": "Firewall Outside", "address": "10.10.10.230/30"}


How can I remove all u' from the get data or from the data I am 
attempting to post?


Cheers\
--
https://mail.python.org/mailman/listinfo/python-list


UG Announcement - Python Tanzania Community

2019-10-15 Thread Noah .
Dear Listers,

As per requirements, we are pleased to announce the existence of the Python
language community in Tanzania.

Please find below some information and the current developments.

*User Group Details;*

Name: Python Community Tanzania
Mailing list: https://mail.python.org/mailman3/lists/tanzania.python.org/
Under Other: Africa
First Local Meetings Held: Yes

*Meetings and Events;*

Name: PyCon Tanzania
Website: pycon.or.tz
Github:  https://github.com/pycontanzania
Under Other: Africa
Organizing Members: 5 - 10

Goal and motivation: To build and sustain while bringing together and
growing the Python language users and community in Tanzania through Python
related meetups, workshops and annual events.

FWIW, Tanzania is a peaceful nation formed out of the political union
between (Tanganyika and Zanzibar ) in the East African Region. The land of
the Serengeti Game Park and the tallest mountain in Africa, the Kilimanjaro.

For more about Tanzania [1] http://www.tanzania.go.tz/home/pages/68

Cheers,
Noah
Community Moderator
https://twitter.com/PyconTanzania
-- 
https://mail.python.org/mailman/listinfo/python-list


Library Generate a diff between two text files

2019-11-25 Thread Noah
Hi Folks,

>From experience, could someone point me to a library that can do a diff
between two separate text files...

*difflib* doesn't seem to cut it to this end....

*./noah*
neo - network engineering and operations
-- 
https://mail.python.org/mailman/listinfo/python-list


[osx] dyld: Library not loaded: /usr/local/Cellar/python@3.8/3.8.3_1/Frameworks/Python.framework/Versions/3.8/Python

2020-12-04 Thread Noah

Hi there,

Anybody know how to fix this issue on a mac?

❯ /usr/local/bin/python
dyld: Library not loaded: 
/usr/local/Cellar/python@3.8/3.8.3_1/Frameworks/Python.framework/Versions/3.8/Python

  Referenced from: /usr/local/bin/python
  Reason: image not found
[1]32209 abort  /usr/local/bin/python

Cheers
--
https://mail.python.org/mailman/listinfo/python-list


expanding dictionary to function arguments

2005-11-02 Thread Noah
I have a dictionary that I would like to expand to satisfy a
function's agument list. I can used the ** syntax to pass a dictionary,
but
this only works if each key in the dictionary matches an argument.
I cannot pass a dictionary that has more keys than the function has
arguments.

# Example 1 - This works:
# Prints "hello world!"
def foo (arg1='greetings', arg2='planet', arg3='.'):
print arg1 + ' ' + arg2 + arg3
args = {'arg1':'hello', 'arg2':'world', 'arg3':'!'}
foo (**args)

# Example 2 - This does not work:
# raises TypeError: foo() got an unexpected keyword argument 'arg4')
def foo (arg1='greetings', arg2='planet', arg3='.'):
print arg1 + ' ' + arg2 + arg3
args = {'arg1':'hello', 'arg2':'world', 'arg3':'!', 'arg4':'ignore'}
foo (**args)

As a practical application, I have a project where I have a config file

that defines a large number of keys and values. I read the config
file into a dictionary called "options". I also have an API module with
many
functions that I want to call with arguments taken directly from the
"options" dictionary. The key names in the "options" dictionary match
the argument names  of the functions in my API.

# The ugly, brutish way:
options = read_config ("options.conf")
extract_audio (options['source_video_filename'])
compress_audio (options['audio_raw_filename'],
options['audio_compressed_filename'], options['audio_sample_rate'],
options['audio_bitrate'])
mux (options['source_video_filename'],
options['audio_compressed_filename'], options['output_video_filename'])

I know that the keys in my "options" dictionary match the arguments
of the functions in the API library, so I would like to do this:
options = read_config ("options.conf")
extract_audio (**options)
compress_audio (**options)
mux (**options)

I created the following function to do what I am describing.
This isn't too bad, but I thought that perhaps there was some
secret Python syntax that will do this for me.

def apply_smart (func, args):
"""This is similar to func(**args), but this won't complain about
extra keys in 'args'. This ignores keys in 'args' that are
not required by 'func'. This passes None to arguments that are
not defined in 'args'. That's fine for arguments with a default
valeue, but
that's a bug for required arguments. I should probably raise a
TypeError.
"""
if hasattr(func,'im_func'): # Handle case when func is a class
method.
func = func.im_func
argcount = func.func_code.co_argcount
required_args = dict([(k,args.get(k)) for k in
func.func_code.co_varnames[:argcount]])
return func(**required_args)

So, I now I can do this:
options = read_config ("options.conf")
apply_smart (extract_audio, options)
apply_smart (compress_audio, options)
apply_smart (mux, options)

Neat, but is that the best I can do?

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: expanding dictionary to function arguments

2005-11-02 Thread Noah

Bruno Desthuilliers a écrit :
> Noah a écrit :
> If you have control over the API functions declarations, makes them so:
> def my_api_func(arg1='', arg2='whatever', **kwargs):
>code_here

Unfortunately I cannot change the API functions.
I should have mentioned that.

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


How can I package a python script and modules into a single script?

2005-11-03 Thread Noah
I would like to package my main script and all the
modules it imports into a single script that will
run just as the collection would. It should not
need to package standard Python lib modules -- just
my local modules. This is not the same question
that would be answered with py2exe or py2app. I
don't need to package the script into a binary
along with Python. I expect Python to be installed.
I also don't want to use distutils to install the
script. The script will always run on Unix.

I thought that there might be some way to run a
script package from a tar file. One way would be to
have the package script  untar itself into a temp
directory; run the main script; then  delete the
temporary package directory when done. That sounds
clunky and prone to leave around trash if someone
does a 'kill -9'. However, this might be an
acceptable compromise. I'm sure that I've seen a
tool around like this, but I can't find it anymore.
I checked the usual places (google and sf.net).

I also considered simply cutting and pasting all
the modules I need into one single, giant script,
but that's less appealing than the tarball idea
(unless it could be done automatically).

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I package a python script and modules into a single script?

2005-11-03 Thread Noah
Freeze also packages the python interpreter into a binary.
I need a cross platform solution that just packages the scripts.
I expect the user to already have python installed.

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I package a python script and modules into a single script?

2005-11-03 Thread Noah
Bingo! That is what I was thinking of.
http://effbot.org/zone/squeeze.htm
It turns out that it doesn't quite do what I want
because the resulting script is tightly coupled
to the version of Python used to build the package.
It compiles the PYC byte-code into the package.
It's neat and I may be able to use the ideas to do
what I want.

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I package a python script and modules into a single script?

2005-11-03 Thread Noah
This is interesting, but requires two separate files -- the ZIP file
and the boot script.
This is because zipimport can only import from file paths.
It can't import from a string or an IOString (as far as I can tell).
If only they would let you import from an already open file. Damn!

Squeeze is 99% of what I want except for the fact that it precompiles
the py files to bytecode
which locks you to the version of python you compiled on. Python byte
code is not guaranteed
to be portable across different versions of Python. Squeeze relies on
ihooks, which is
a standard module, but it is undocumented.

Anders Hammarquist has a Python Cookbook example that seems to do what
I want.
"Importing a Dynamically Generated Module". So far so good. I have to
check it out a bit more.
It relies on the "imp" standard library module.

With a bit of inspiration from "Squeeze" and help from the "imp" module
I might have what I want.

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I package a python script and modules into a single script?

2005-11-22 Thread Noah
Alex Martelli wrote:
>
> > This is because zipimport can only import from file paths.
>
> It can import from a file, and the file (like all zipfiles) can have a prefix
> That prefix is where you put the "boot" script.
> See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/215301

Unfortunately, Raedler's boot script closes stdin, which is a fairly
big limitation.
The herefile in the shell script (END_OF_PYTHON_CODE) redirects stdin
before
python starts; stdin is closed at the end of the herefile. This
disables raw_input()
and anything else that reads sys.stdin. Enter the following at a shell
prompt
to demonstrate the problem:
python - << HEREFILE
> print raw_input("Enter something")
> HEREFILE
You will get the following error:
Enter somethingTraceback (most recent call last):
  File "", line 1, in ?
EOFError: EOF when reading a line

But all is not lost. The "zipheader.unix" script can be rewritten to
use the '-c' option of python
instead of stdin and a herefile. This also handles the case where
Python may be even less
than version 2.0. This works the same. Just "cat zipheader.unix
main.zip > main" then run "main".

 8<  8<  save as zipheader.unix  8<  8<
--
#!/bin/sh
# This is a self-extracting executable.
# Execute this like any normal executable.
# You may need to "chmod a+x" this file.
# This is a binary ZIP file with a Python loader header.
#
# Bourne shell loader:
PYTHON=$(which python 2>/dev/null)
if [ ! -x "$PYTHON" ] ; then
echo "Python not found!"
exit 1
fi
exec $PYTHON -c "
# Python loader:
import sys, os
if int(sys.version[0])<2:
print 'Python version 2.3 final or greater is required.'
print 'Your version is', sys.version
os._exit(1)
major = sys.version_info[0]
minor = sys.version_info[1]
releaselevel = sys.version_info[3]
if (major==2 and minor<3) or (major==2 and minor==3 and
releaselevel!='final'):
print 'Python version 2.3 final or greater is required.'
print 'Your version is', sys.version
os._exit(1)
sys.path.insert(0, sys.argv[1])
del sys.argv[0:1]
print sys.argv[1]
import main
main.main()
" $0 $@

# Zip file:
 end of zipheader.unix
---

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newby question: Splitting a string - separator

2005-12-08 Thread Noah

Thomas Liesner wrote:
> ...
> The only thing i can rely on, ist that the
> recordseparator is always more than a single whitespace.
>
> I thought of something like defining the separator for split() by using
>  a regex for "more than one whitespace". RegEx for whitespace is \s, but
> what would i use for "more than one"? \s+?

For your split regex you could say
"\s\s+"
or
"\s{2,}"

This should work for you:
    YOUR_SPLIT_LIST = re.split("\s{2,}", YOUR_STRING)

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Modules for inclusion in standard library?

2005-06-29 Thread Noah

unzip() -- Not really a module, but a standard library function.
Why isn't it in the standard library?
It seems like I'm always adding it to my code.
I think I once heard an argument against it, but I forget what it was.
And yet I still find myself wanting unzip.

def unzip(list):
if len(list) == 0: return ()
l = []
for t in range(len(list[0])):
l.append(map( lambda x,t=t: x[t], list ))
return tuple(l)

Yours,
Noah

Reinhold Birkenfeld wrote:
> Hello,
>
> at the moment python-dev is discussing including Jason Orendorff's path module
> into the standard library.
>
> Do you have any other good and valued Python modules that you would think are
> bug-free, mature (that includes a long release distance) and useful enough to
> be granted a place in the stdlib?
>
> For my part, ctypes seems like a suggestion to start with.
> 
> Reinhold

-- 
http://mail.python.org/mailman/listinfo/python-list


Can I get message filename from a Maildir mailbox stream?

2005-02-18 Thread noah
Is there a way to figure out what
filename an email object points to in a
qmail style Maildir directory?

Hmmm... I don't think so, but I'm hoping I wrong.

I instantiated a Maildir mailbox and I'm
iterating through the messages. When I find a
special message I want to move it or delete it
or something. 

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I get message filename from a Maildir mailbox stream?

2005-02-22 Thread Noah
This didn't work. I'm using the standard Python 2.3.4 library
mailbox.Maildir. I got an error that message instance
has no attribute 'fp'.

I ended up not using mailbox.Maildir at all.
It occured to me that since Maildir style mailboxes
is just a collection of files that it was simpler to write
a generator that walked the directory using os.listdir.

def Maildir_messages (path):
d = os.listdir(path)
for filename in d:
fin = file (os.path.join(path, filename))
yield (email.message_from_file(fin), filename)
fin.close()

for msg, msg_filename in Maildir_messages ("/home/noah/Maildir/new"):
print msg_filename
    print msg['Subject']

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comm. between Python and PHP

2005-02-22 Thread Noah
It wasn't quite clear, but I assume that you want a PHP script that
can call on the Python daemon and not have the daemon make
calls to a PHP script.

You could use xml-rpc which is built into Python as of version 2.2:
http://docs.python.org/lib/module-xmlrpclib.html
On the PHP side xmlrpc is still experimental. You have to
enable this when you build PHP:
http://us3.php.net/manual/en/ref.xmlrpc.php

You could also just add a simple HTTP interface to your daemon.
It's pretty easy to add an HTTP interface to your daemon.
Look at SimpleHTTPServer the docs:
http://docs.python.org/lib/module-SimpleHTTPServer.html
You will also need to read the source for SimpleHTTPServer.py to
figure out how it works (I don't know why they don't just put the
example
in the docs instead of putting the example in the source).

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: capturing text from a GUI window

2005-03-08 Thread noah

Earl Eiland wrote:
> Anyone know how to capture text from GUI output?  I need to process
> information returned via a GUI window.
>
> Earl

Assuming Windows, then these guys have an interesting tool:
http://www.skesoft.com/textcatch.htm
It's not free, but you can try it before you buy it.
You will need COM to control it from Python.

Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


How to create stuffit files on Linux?

2005-03-15 Thread Noah
I need to create Stuffit (.sit) files on Linux.
Does anyone have any ideas for how to do this?
I checked the Python docs and on SourceForge, but
I didn't see any open source stuffit compatible libraries.
Are my Mac users out of luck?

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to create stuffit files on Linux?

2005-03-16 Thread Noah
The problem is that my users want to see .sit files.
I know it's sort of silly. Zip files are foreign and frightening to
them.
I mentioned zip files, but they didn't want to deal with them.

Is there a native OS X archive or package format?
Obviously it must have tar and gzip installed, but I wonder
how a *.tgz file would appear on the desktop or how the
GUI would handle it. 

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


netaddr value back to IP

2014-11-13 Thread Noah

Hi there List,

I am trying to get a value back to IP using the netaddr python module.
How do I get the value 'ip' back to IP format?  how is it done?

 snip 

print IPNetwork(v4_peer_ip).value
ip = IPNetwork(v4_peer_ip).value + 1
print ip

--- snip ---

Cheers,
Noah
--
https://mail.python.org/mailman/listinfo/python-list


finding the diff

2015-09-10 Thread Noah

Hi there,

I am researching a nice slick way to provide the difference between 
generated python multi-line configuration output and specific 
configuration lines gathered from an output file.  I could put things in 
a list?   I could put both forms output into IOString() and run a diff 
command to it?


What are some options that work well?

Cheers,

Noah
--
https://mail.python.org/mailman/listinfo/python-list


beginners python mail list

2014-06-21 Thread Noah

HI there,

I have some amateur python questions.  Is there a beginners python mail 
list?


Cheers,

Noah
--
https://mail.python.org/mailman/listinfo/python-list


python template lint

2014-07-25 Thread Noah

Hi there List,

I am looking for a little guidance here.  I am taking a series of 
template files for building configuration.  I want to design some simple 
lint rules to check for some of the syntax of the template files I 
created.  For instance if an open brace is seen indent 4 spaces each 
time.  unindent when a close brace is seen.  remove blank lines. Remove 
comments after '#' and so on.  I could write this with search adn 
replace rules but I might want a module that allows for some complexity 
down the road.


Any cool python module recommendations out there that does this well?

Cheers,

Noah
--
https://mail.python.org/mailman/listinfo/python-list


reading text files with indentation

2014-07-28 Thread Noah

Hi there,

The following code I am using to read in lines from a text file.  The 
indentation of the text is getting lost.  How can I correct that?



for file in files:
with open (file, "r") as file:
lines = file.readlines()

for line in lines:
line = re.sub("#.*", "", line)
line = line.strip()
policy_lines.append(line)
print line

Cheers
--
https://mail.python.org/mailman/listinfo/python-list


xml issue with Type 'bool' cannot be serialized

2014-08-28 Thread Noah

Hi list,

I am not clear how to fix this issue.

Traceback (most recent call last):
  File "./command.py", line 81, in 
connect(host, USER, PASSWORD)
  File "./command.py", line 63, in connect
dump = etree.tostring(xml_cmd)
  File "lxml.etree.pyx", line 3165, in lxml.etree.tostring 
(src/lxml/lxml.etree.c:69414)

TypeError: Type 'bool' cannot be serialized.


here is snippets from the code



--- code ---

from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from lxml import etree
import jnpr.junos.exception
import sys, os, time, re, getopt

def connect(host, user, password):
conn = Device(host=host, user=user, password=password).open()

xml_cmd = ''
xml_cmd = conn.rpc.get_configuration()
dump = etree.tostring(xml_cmd)
print dump

--
https://mail.python.org/mailman/listinfo/python-list


Re: Parsing text

2005-12-19 Thread Noah
sicvic wrote:
> I was wondering if theres a way where python can read through the lines
> of a text file searching for a key phrase then writing that line and
> all lines following it up to a certain point, such as until it sees a
> string of "-"
>...
> Thanks,
> Victor

You did not specify the "key phrase" that you are looking for, so for
the sake
of this example I will assume that it is "key phrase".
I assume that you don't want "key phrase" or "-" to
be returned
as part of your match, so we use minimal group matching (.*?)
You also want your regular expression to use the re.DOTALL flag because
this
is how you match across multiple lines. The simplest way to set this
flag is
to simply put it at the front of your regular expression using the (?s)
notation.

This gives you something like this:
print re.findall ("(?s)key phrase(.*?)-",
your_string_to_search) [0]

So what that basically says is:
1. Match multiline -- that is, match across lines (?s)
2. match "key phrase"
3. Capture the group matching everything (?.*)
4. Match "-"
5. Print the first match in the list [0]

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: show in GUI stdout of a command

2005-12-19 Thread Noah
Try Pexpect for running your command interactively
http://pexpect.sourceforge.net/

For example, if you wanted to run the "top" command you could
use a script like below. This updates the output every 5 seconds.
You can easily adjust the timeout.
---
import pexpect
def progress_callback (d):
"""This callback updates child command output.
This is used when running external commands
with pexpect.run.The callback is given a dictionary
of the local variables in pexpect.run. This explains
the syntax of d['child'].before, which you would
otherwise simple enter as child.before.
"""
print d['child'].before

pexpect.run("top", timeout=5,
events={pexpect.TIMEOUT:progress_callback})
---

Next you would then have to add that whole
GUI thing yourself :-)

You can also try using pipes (popen and friends), but the
output will be block buffered, so it would come out chunky
and not in real time. There is no way to change the child's
buffering from block buffering to line buffering without using
a pseudo-TTY.

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread Noah
So you are saying that something like this would not work for you?

current_record_value = get_value_in_database ('record_key')
new_record_value = raw_default ("Enter new record value",
current_record_value)
set_value_in_database ('record_key', new_record_value)

Maybe you are confusing this with TAB completion at the shell command
line.

I often use my own default_input function. I also add the ability to
HELP text
to the prompt, so if the user enters '?' then extra information is
printed.
Of course, that means 

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IMAP4 Memory Error

2005-12-22 Thread Noah
This looks like a bug in your build of Python 2.4.2 for Windows.
Basically it means that C's malloc() function in the Python interpreter
failed.

You can catch this exception to try to recover. Here is an example:

try:
typ, data = M.fetch(num, '(RFC822)')
exception MemoryError, e:
print "Could not get message number", num
print "IMAP4.fetch failed due to a MemoryError"
print str(e)
import platform
if platform.version() == "2.4.2":
print "This is Python 2.4.2"
print "You have a buggy build of Python. Try another."

You could also try IMAP4.partial() which looks like it might allow
you to retrieve part of the message (I can't be sure because the
docs are not very detailed). Loop through and get 1 MByte at a time.
I have no idea if partial() is intended to be used this way.
It doesn't even say what happens if there is no more data or
if the amount of data you request is longer than what is available.
You will have to experiment.

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: serialize object in jython, read into python

2005-12-22 Thread Noah
py wrote:
> I want to serialize an object in jython and then be able to read it in
> using python, and vice versa.
>
> Any suggestions on how to do this?  pickle doesnt work, nor does using
> ObjectOutputStream (from jython).
>
> I prefer to do it file based ...something like
>
> pickle.dump(someObj, open("output.txt", "w"))
>
> as opposed to shelve
>
> f = shelve.open("output.txt")
> f['somedata'] = someObj
>
> Thanks for the help in advance.

You can give up on pickle, because pickle is only
guaranteed to work with the exact same version of the Python
interpreter.
(It will work on the same version of the Python interpreter on
different platforms, but
that's probably not useful to you here).

How complex of a serialization do you need?
Would simply saving a dictionary of strings work for you?
That's what I do for HTTP session management.
I then map my session dictionary to the dictionary of object
attributes.

You might also consider JSON which is very simple and lightweight.
http://www.json.org/

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


How do I get a dictionary of argument names with their default values?

2005-12-22 Thread Noah
Is there a simple way to get a dictionary of
argument names and their default values for
a method or function? I came up with one solution, but
I feel like Python must have a simpler way.

Python provide a way to get a sequence of
argument names and a different way to get a
sequence of default argument values. Since
default values have to come at the end of an
argument list you can match up the values in the
default values sequence to the values in the
argument list sequence.

The following seems to work on both functions and methods::

def func_arg_defaults_dict (func):
default_dict = {}
if func.func_defaults is not None:
da_start = len(func.func_code.co_names) -
len(func.func_defaults)
for i in range(len(func.func_defaults)):
arg_name = func.func_code.co_names[da_start+i]
arg_value = func.func_defaults[i]
default_dict [arg_name] = arg_value
return default_dict

def foo (f1, f2, f3, f4='F4', a5='F5'):
print f1, f2, f3, f4, f5

class fu:
def foo (self, m1, m2, m3, m4='M4', m5='M5'):
print m1, m2, m3, m4, m5

f = fu()

# test function
print func_arg_defaults_dict (foo)
# test method
print func_arg_defaults_dict (f.foo)

Running the script prints this::

{'f4': 'F4', 'f5': 'F5'}
{'m5': 'M5', 'm4': 'M4'}

Is func_arg_defaults_dict() reasonable? It seems a bit convoluted.
I hope there is a more obvious way.

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I get a dictionary of argument names with their default values?

2005-12-22 Thread Noah

Thanks! Much more handy than what I was trying to do
and it looks like I might even learn something new :-)

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Detect File System changes

2005-12-23 Thread Noah
In the UNIX world the common tool is FAM -- File Allocation Monitor.
This is a daemon that will report filesystem changes to clients.
There is a Python interface to libfam called "Python FAM" here:
http://python-fam.sourceforge.net/
It looks mature, but I have never used it.

There are also some alternatives to FAM, but I don't remember the names
of them right now.

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


How to reverse tuples in a list?

2006-08-08 Thread Noah
I have a list of tuples
[('a', 1.0), ('b', 2.0), ('c', 3.0)]
I want to reverse the order of the elements inside the tuples.
[(1.0,'a'), (2.0, 'b'), (3.0, 'c')]

I know I could do this long-form:
q = []
y = [('a', 1.0), ('b', 2.0), ('c', 3.0)]
for i in y:
t=list(t)
t.reverse()
q.append(tuple(t))
y = q

But it seems like there should be a clever way to do this with
a list comprehensions. Problem is I can't see how to apply
reverse() to  each tuple  in the list because reverse() a
list method (not a tuple method) and because it operates
in-place (does not return a value). This kind of wrecks doing
it in a list comprehension. What I'd like to say is something like
this:
y = [t.reverse() for t in y]
Even if reverse worked on tuples, it wouldn't work inside a
list comprehension.

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


super and __init__

2006-09-08 Thread Noah
Am I the only one that finds the super function to be confusing?

I have a base class that inherits from object.
In other words new style class:

class foo (object):
def __init__ (self, arg_A, arg_B):
self.a = arg_A
self.b = arg_B
#   Do I need to call __init__ on "object" base class?

class bar (foo):
def __init__ (self, arg_Z):
self.z = "Z" + arg_Z
foo.__init__(self, 'A', arg_Z)#  this is the old-style
class way
def __str__ (self):
return self.a + self.b + self.z

I don't know how people will use the "bar" class
in terms of inheritance. I don't want to lock anyone
out of multiple inheritance, but I'd like to  have to
worry about it as little as possible. From what I've
read using  the  old style of calling the
base class __init__ can cause conflicts
if the class is later part of a diamond relationship.

I just want "bar" to initialize the properties that it add
to the base class and to have it tell the base class to
initialize the inherited properties. The old way seemed
clear enough; although, a bit ugly. The super function
seems like it would make this more clear, but
it doesn't (to me).

Is there a "just do this" answer for 90% of the use cases?

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: super and __init__

2006-09-08 Thread Noah

Jason wrote:
> Noah wrote:
> > Am I the only one that finds the super function to be confusing?
>
> Unfortunately, I don't see a way of avoiding this problem with super().
>  Any such super command resolves in the mro order.  Since the mro order
> invoked at a certain class can change depending on its subclasses,
> there's no way for the class to predict at design time what super() is
> going to return.  You can predict what will be returned with your class
> hierarchy, but another programmer can create a multiple-inheritence
> class that will change the result.
>
> Explicitly calling the base class is much easier, but a given class
> method can be called multiple times in that case.

If I know that multiple calls to my base class __init__ is harmless
and multiple calls to my derrived class __init__ is harmless then
is it best to just go ahead and use the old style of explicitly calling
the __init__? I'm just worried about using the old style base __init__
call
with new style objects.

Since inheritance is so fundemental to an object oriented language
it's bad that Python makes it so easy to get the constructor wrong.

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Can a test case tell if VERBOSE is used in pyunit test?

2006-01-30 Thread Noah
Is there a way for a test case method in a class derived
from unittest.TestCase to tell if the harness was started
with the verbose option? I would like my test cases to
print out a little extra information if the tests were run with
-v or -vv.

yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running python cgi scripts that require external cvs under apache

2005-05-06 Thread Noah
How do you run the cvs binary from your script? If this is a simple CGI
that calls os.popen() or os.system() then the cvs binary is most likely
running as the same user as the Apache HTTP server (usually someone
like "nobody", "apache", or "www").  http://cgiwrap.unixtools.org/ is
one solution.  Also consider suEXEC  which is part of the Apache
distribution; although, it is not installed by default. See
http://httpd.apache.org/docs/suexec.html . There are reasons why this
is dangerous and those reasons are discussed in the suEXEC
documentation. You can also see if the system administrator can allow
the web server user or group to run cvs. Again, this exposes your
server and so it's dangerous, but allowing cvs commit from a CGI is
dangerous, so I assume you know what you are doing. All of these
solutions will require the involvement of your UNIX system
administrator.

You may also want to look at the ViewCVS project
(http://viewcvs.sourceforge.net/ ) since that is written in Python and
implements a CGI-to-cvs interface. This may give you some
implementation hints.

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug/Weak Implementation? popen* routines can't handle simultaneous read/write?

2007-06-07 Thread Noah
On Jun 7, 9:01 am, dmoore <[EMAIL PROTECTED]> wrote:

popen and friends will never do what you want it to do. Down that path
lies bitter disappointment.
You need pseduo-ttys and non-blocking IO. I don't know how to do this
on Windows, but I know it's possible.
Cygwin does it.

> Anybody have any thoughts on this? Do I have my story straight? (the
> popen variants can't handle this case and there are no other
> alternatives in the standard python distro) Is there some place I can
> submit this as a feature request? (Python dev?)

Try Pexpect http://pexpect.sourceforge.net/
It's been around for a long time and is quite complete and stable.

The catch is that it's UNIX-only. If you want to tease out the magic
code from wxProcess that
does non-blocking reads on win32 then I'd be happy to integrate that
into the current development branch
of Pexpect. If someone can provide a pure Python drop-in replacement
for the read_nonblocking() function
I use for UNIX systems then it would be easy. I have a whole test
framework that I can run it through to
see if it performs the same as the UNIX flavor.

I'm sure this is feasible without any C extensions -- it might require
some ctypes hacking.
I know Windows has pretty decent async IO, but I don't know what they
have as an equivalent for a pty.
Maybe it isn't necessary. A pty is only necessary on UNIX because the
standard c library, stdio, behaves
differently when it's talking to a plain pipe versus a terminal -- it
switches buffering
between block and line oriented buffer. You don't want block buffering
on interactive applications.
This is why popen eventually breaks down. No, there is no way to
select this behavior from
the calling side... unless you can trick it into dynamically linking
to your specially hacked libc.
But that's getting ahead because that's what happens on UNIX -- it
might be a non-issue on Windows.

The read_nonblocking() function I use has an interface like this:

def read_nonblocking (self, size = 1, timeout = -1):

"""This reads at most size characters from the child
application. It
includes a timeout. If the read does not complete within the
timeout
period then a TIMEOUT exception is raised. If the end of file
is read
then an EOF exception will be raised. If a log file was set
using
setlog() then all data will also be written to the log file.

If timeout is None then the read may block indefinitely. If
timeout is -1
then the self.timeout value is used. If timeout is 0 then the
child is
polled and if there was no data immediately ready then this
will raise
a TIMEOUT exception.

The timeout refers only to the amount of time to read at least
one
character. This is not effected by the 'size' parameter, so if
you call
read_nonblocking(size=100, timeout=30) and only one character
is
available right away then one character will be returned
immediately.
It will not wait for 30 seconds for another 99 characters to
come in.

    This is a wrapper around os.read(). It uses select.select() to
implement the timeout. """


Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with PEXPECT in Python

2007-07-02 Thread Noah

Kevin Erickson wrote:
> On Jun 30, 5:50 pm, Kevin  Erickson <[EMAIL PROTECTED]> wrote:
> > #Begin Code
> >
> > import sys
> > import pexpect
> >
> > def GetServerData(self):
> > foo = pexpect.spawn('scp [EMAIL PROTECTED]:/home/config/
> > role{/file1,/files/file2,/files/file3} /tmp')
> > foo.expect('.*password:*')
> > foo.sendline('server_password')
> > foo.interact()
...
> I have found a work around for my problem.  I replace the following line:
>
> foo.interact()
> with
> foo.expect(pexpect.EOF)

That is correct. But why did you try using interact() method in the
first place?
I just want to know to see if I could improve the documentation.
After you send the password the 'scp' command should finish quickly
and exit,
so there would be nothing for a human to interact with.

You could also try using the run() function which is a simplified
interface to pexpect.
Something like this might work:
pexpect.run ('scp [EMAIL PROTECTED]:/home/config/role{/file1,/files/
file2,/files/file3} /tmp',
events={'(?i)password': 'server_password'})
That's all there is to it. The run() function will run the given scp
command.
When it see 'password' in the output it will send the server_password.

Yours,
Noah


Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Subprocess module

2007-07-15 Thread Noah
On Jul 13, 2:15 pm, Dave Sampson <[EMAIL PROTECTED]> wrote:
> hey folks,
>
> A simple question hopefully. despite all my searching I have not found a
> satisfactory response.
>
> The goal. Interact with a command line program. Simple enough, but the
> key is INTERACT.

You need Pexpect.

> So then I went with Popen and such... which then led to the subprocess
> module. I can create the object and read a few lines of output. but if I go 
> too
> far then the program hangs. the number of lines will differ depandening
> on many function including the format of an input file so I can;t
> hardcode how many lines to read.

There is nothing you can do about this when using a pipe.
This is because stdio will change the type of buffering when sending
stdout and stderr to a pipe. From the client side there is no way you
can change the buffer mode (you CAN change the mode, but it only
changes
it on YOUR side of the pipe -- not your child application's side).

> and nothing seems to get the program going again for I still cant; read
> past the same point in the standard output. then I have to kill and
> start over.

Your child application is waiting for you, but you can't see what it
wrote
becuase it has not filled or flushed the output buffer. When a program
write to stdout and it is connected to a TTY it will automatically
flush
the output buffer when it writes a newline (or, rather, the clib will
do this).
But when writing to a pipe it will automatically use block buffering
and
will only flush the buffer when it is full.

It's not very complicated, but it can be very confusing at first.
It is also surprising that this behavior cannot be changed by the
parent application.

> So the next approach included looking atPexpect, which got realy
> confusing realy fast and despite running fedora core and python 2.4.4 I
> would like my application to be cross platform and there is noPexpect
> for Windows That I can see.

You are going to need something like Pexpect that uses pseudo-ttys
(pty).
Pexpect works under Cygwin on Windows, but not under the native
Windows Python.

Email me if you have questions about Pexpect and I'll try to help you.

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


How do I use trace to generate coverage data in multi-threaded programs?

2007-12-19 Thread Noah
I'm trying to use the trace module to build coverage files for
a multi-threaded program.

http://docs.python.org/lib/module-trace.html

I test my application using trace.py from the command-line like this:

/usr/lib/python2.5/trace.py --missing --count --summary tools/
testall.py

When I examine the *.cover files that are generated after a test run
I do not see coverage information for the methods that were run
in a separate thread. How can I collect coverage information for
methods that only run in a separate thread (never in the main thread)?

Any tips?

--
Noah Spurrier
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I use trace to generate coverage data in multi-threaded programs?

2007-12-20 Thread Noah
On Dec 19, 7:33 pm, Noah <[EMAIL PROTECTED]> wrote:
> /usr/lib/python2.5/trace.py --missing --count --summary tools/testall.py
>
> When I examine the *.cover files that are generated after a test run
> I do not see coverage information for the methods that were run
> in a separate thread. How can I collect coverage information for
> methods that only run in a separate thread (never in the main thread)?

Just for the record, the problem was due to the fact that I was
creating threads
using the "thread" module. When I switched to creating threads using
the
"threading" module I was able to see my thread code in coverage
reports.

--
Noah Spurrier
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why my program (using pexpect to switch user) doesn't work well?

2008-01-10 Thread Noah
On Jan 10, 12:59 am, BlackjadeLin <[EMAIL PROTECTED]> wrote:
> I'm new to python
> I want to write a simple script to switch user,for example,from user_A
> to user_B.
> This my codes:
>
> #!/usr/bin/python
> importpexpect
> import os
> passwd="user_B"
> child =pexpect.spawn('su user_B')
> child.expect('Password:')
> child.sendline(passwd)
> child.expect('$')
> child.close()
>
> Maybe it's the easiest pexpect program.Sometimes ,it work well,it
> switch to user_B successfully .But after i type the command exit to
> switch back to user_A,execute the python script again,it can't work,do
> nothing or just waiting.Why it have different results?
> Sorry for my poor English,and many thanks to all.
>
> Blackjade

When you call child.close() that will kill the child process.
Possibly you want to use the interact() method.
It is not clear from your message if you want to interact with
the child process as if it were your new shell. If you do,
then take a look at the interact() method.

  #!/usr/bin/python
  importpexpect
  import os
  passwd="user_B"
  child =pexpect.spawn('su user_B')
  child.expect('Password:')
  child.sendline(passwd)
  child.expect('$')
  child.interact()

--
Noah
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What should I use under *nix instead of freeze?

2008-02-01 Thread Noah
On Feb 1, 3:08 pm, Mike Kent <[EMAIL PROTECTED]> wrote:
> In a comment Guido made on a recent bug report for the 'freeze'
> utility, he stated:
>
> "I think nobody really cares about freeze any more -- it isn't
> maintained."
>
> That being the case, what is the preferred/best replacement for freeze
> on a *nix platform?  I'm looking for something that, like freeze,
> turns my application into a single-file executable, of the smallest
> size possible, that can be executed on a machine with no Python
> installation or development system.

This isn't a complete answer -- it requires Python, but
you might figure out a way to also embed an interpreter and
libraries.
I remember seeing such an installation somewhere (I think on
SourceForge),
but I don't remember the name of it. At any rate, this explains how
to
package your python project and libs as a self-extracting compressed
executable:

http://www.noah.org/wiki/Python_zip_exe

--
Noah Spurrier
-- 
http://mail.python.org/mailman/listinfo/python-list


How do I iterate over items in a dict grouped by N number of elements?

2008-03-13 Thread Noah
What is the fastest way to select N items at a time from a dictionary?
I'm iterating over a dictionary of many thousands of items.
I want to operate on only 100 items at a time.
I want to avoid copying items using any sort of slicing.
Does itertools copy items?

This works, but is ugly:

>>> from itertools import *
>>> D = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10}
>>> N = 3
>>> for G in izip(*[chain(D.items(), repeat(None, N-1))]*N):
... print G
...
(('a', 1), ('c', 3), ('b', 2))
(('e', 5), ('d', 4), ('g', 7))
(('f', 6), ('i', 9), ('h', 8))
(('j', 10), None, None)

I'd prefer the last sequence not return None
elements and instead just return (('j',10)), but this isn't a huge
deal.

This works and is clear, but it makes copies of items:

>>> ii = D.items()
>>> for i in range (0, len(ii), N):
... print ii[i:i+N]
...
[('a', 1), ('c', 3), ('b', 2)]
[('e', 5), ('d', 4), ('g', 7)]
[('f', 6), ('i', 9), ('h', 8)]
[('j', 10)]

--
Noah
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.2.1 and select()

2008-03-24 Thread Noah
On Mar 24, 2:58 pm, Derek Martin <[EMAIL PROTECTED]> wrote:
> If and only if the total amount of output is greater than the
> specified buffer size, then reading on this file hangs indefinitely.
> For what it's worth, the program whose output I need to capture with
> this generates about 17k of output to STDERR, and about 1k of output
> to STDOUT, at essentially random intervals.  But I also ran it with a
> test shell script that generates roughly the same amount of output to
> each file object, alternating between STDOUT and STDERR, with the same
> results.
>

I think this is more of a limitation with the underlying clib.
Subprocess buffering defaults to block buffering instead of
line buffering. You can't change this unless you can recompile
the application you are trying to run in a subprocess or
unless you run your subprocess in a pseudotty (pty).

Pexpect takes care of this problem. See http://www.noah.org/wiki/Pexpect
for more info.

--
Noah
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Control process execution

2008-04-09 Thread Noah
On Apr 6, 5:30 am, Wesley Mesquita <[EMAIL PROTECTED]> wrote:
> I am trying to create a test environment to a couple C applications
> (simple UDP and TCP server/clients), so I want to write this in python
> and I m looking for ways to do it. Basically I need an execution timer
> and timeout control (to kill the apps in certain situations). Looking
> at google, I found the Pexpect package, but I m a little bit lost in
> using it.

Pexpect might be good. But if you are just looking at running an
application
without talking to it interactively then you might be able to just get
by
with os.process.

--
Noah
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Control process execution

2008-04-09 Thread Noah
On Apr 9, 1:57 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote:
> As far as I know, there is no "os.process". Maybe you meant os.system
> or the subprocess module?
>
> Mike

Yeah, I was thinking "subprocess" module.
--
Noah
-- 
http://mail.python.org/mailman/listinfo/python-list


Where are Tkinter event.type constants defined?

2008-05-04 Thread Noah
I'm trying to match against Event.type for KeyPress and ButtonPress.
Currently I'm using integer constants (2 and 4). Are these constants
defined anywhere? The docs talk about KeyPress and ButtonPress, but I
don't see them in any of the Tkinter source files. Are these just
magic values that come out of the TK side of things and are not
defined in Python? Code like this makes me think I'm doing something
wrong:

if event.type == 2:
handle_key_press (event.char)
elif event.type == 4:
do_something_for_button ()
else:
pass # unknown event

(I understand that usually you would bind these function so that they
are called as a callback.)

I don't mind defining the constants myself. I just want to make sure
that I'm not missing something already done for me. Does anyone happen
to have a complete list of Event.type constants?

--
Noah
--
http://mail.python.org/mailman/listinfo/python-list


Re: get the pid of a process with pexpect

2008-05-05 Thread Noah
On May 5, 7:18 am, Karim Bernardet <[EMAIL PROTECTED]> wrote:
> ssh_tunnel = pexpect.spawn (tunnel_command % globals())
> ...
> print ssh_tunnel.pid
>
> but ssh_tunnel is not the pid of the ssh tunnel
>
> Is there a way to get it using pexpect ?

You will notice that you can't get this information even from the
shell. This does not work of course:

ssh -f -N -L 81:localhost:80 [EMAIL PROTECTED]
echo $!

However, this seems to work, but I don't trust it. Certainly it isn't
a real daemon, but this work OK for you if you only need to manage the
tunnel for the duration of your script. Notice that now Bash had the
PID in $! variable:

ssh -N -L 81:localhost:80 [EMAIL PROTECTED] &
TUNNEL_PID=$!
echo $TUNNEL_PID

What command-line are you using for 'tunnel_command'? This is hard
because SSH does not provide a way to get the PID of the tunnel if you
request ssh to go to the background (see the -f option). I always
considered this a bug because it makes scripting hard. Even if you
start the tunnel from a shell you can't use $! to get the PID because
the daemonizing is initiated by ssh. This is not the same use using
the shell to put a command into the background, so the shell won't
know anything about the PID.

I'm not sure if you can put ssh into the background using the shell
and still have the tunnel work. So you might start a tunnel something
like this:

ssh -f -N -L 80:localhost:80 [EMAIL PROTECTED]

But can you also do something like this?

ssh -N -L 80:localhost:80 [EMAIL PROTECTED] &
echo $!

And for that to even work you will have to use Pexpect to start bash.
Remember, Python doesn't start your command in a subshell, so you have
to specify it if you want. So your tunnel command would have to be
something like this:

tunnel_command = '''bash -c "ssh -N -L ...foo... &"'''
ssh_tunnel = pexpect.spawn (tunnel_command % globals())

--
Noah
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do you debug memory usage?

2008-05-06 Thread Noah
On May 6, 6:27 am, David <[EMAIL PROTECTED]> wrote:
> Hi list.
> What is the best way to debug memory usage in a Python script?
> ...
> Are there any tools/modules/etc I can use like this?
> David.

You need to use the debug build of Python to get exact numbers,
but there are a few tricks you can use with the standard build
to detect memory leaks. The simplest thing is to simply watch the
RSS column output of `ps aux` (I'm assuming you are using UNIX).

The other trick I got from Chris Siebenmann
http://utcc.utoronto.ca/~cks/space/blog/python/GetAllObjects
I modified his example a little bit. This does not tell you how
many bytes of memory your running code is using, but it will
show you the number of objects. When looking for memory leaks,
counting the number of objects is sufficient to detect leaks.
For example, say you suspect a function is leaking memory.
You could call it in a loop like this and watch the count of
objects before and after each call.

  while True:
  print "Number objects before:", len(get_all_objects())
  suspect_function()
  print "Number objects after:", len(get_all_objects())

Here is my modified version of Chris' get_all_objects() function.
All I did was force garbage collection using gc.collect().
This makes sure that you are not counting objects that Python has
left in memory, but plans on deleting at some point.

  import gc
  # Recursively expand slist's objects
  # into olist, using seen to track
  # already processed objects.
  def _getr(slist, olist, seen):
  for e in slist:
  if id(e) in seen:
  continue
  seen[id(e)] = None
  olist.append(e)
  tl = gc.get_referents(e)
  if tl:
  _getr(tl, olist, seen)
  # The public function.
  def get_all_objects():
  """Return a list of all live Python objects, not including the
list itself."""
  gc.collect()
  gcl = gc.get_objects()
  olist = []
  seen = {}
  # Just in case:
  seen[id(gcl)] = None
  seen[id(olist)] = None
  seen[id(seen)] = None
  # _getr does the real work.
  _getr(gcl, olist, seen)
  return olist

--
Noah
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do you debug memory usage?

2008-05-06 Thread Noah
On May 6, 2:19 pm, David <[EMAIL PROTECTED]> wrote:
> I want to debug rdiff-backup (Python backup tool for Linux) - it's
> using 2 GB of memory (1GB ram, 1GB swap) on a backup server at work.
> ...
> David

Rsync uses a lot of memory:
   http://www.samba.org/rsync/FAQ.html#4
rdiff-backup uses librsync, not rsync.
I'm not sure if rsync uses librsync, but one could speculate that
they share some code and perhaps some of the same problems.
But 2GB seems excessive unless you are dealing with millions of files.
A memory leak seems more likely.
--
Noah
--
http://mail.python.org/mailman/listinfo/python-list


Re: Your feedback on our free Advanced Python tutorial

2017-07-20 Thread Noah
On 20 Jul 2017 3:03 p.m., "Aude Barral, CodinGame" 
wrote:

Hi everyone,

I am co-founder of a startup called CodinGame.

A few days ago we've launched a project: Tech.io <https://tech.io/>. It's a
free knowledge-sharing platform that allows tech professionals to learn new
programming concepts through hands-on content crafted by volunteers in the
community.

Everything runs on our backend. Our system relies on Docker images so we
can play tutorials and demos of virtually any technology from the browser.

So why this project? Because as more and more resources over the Internet
now need to be paid for (Udacity, Udemy, etc), we want to foster free
online technology education thanks to peer learning. In a sense, we'd like
to become some kind of Wikipedia for tech.

One of the first tutorials our contributors published is about Advanced
Python Features (hope more will be published soon!): https://tech.io/play
grounds/500/advanced-python-features/advanced-python-features



Perfect and thanks for taking your time folks to put this together out
there for free.



I have 2 questions for you:

- Do you think this tutorial could be helpful to your Python user
community?


100% Yes


- Would you be willing to help us spread the word about Tech.io?



Yes yes yes...


Thanks a lot for checking,

Cheers!
Aude



Cheers,
Noah

-
Evolve or Extinct. Enable IPv6 now?
-- 
https://mail.python.org/mailman/listinfo/python-list


easy_install says "not a recognized archive type" Windows Py3

2012-10-15 Thread Noah Coad
Hello, I'm new to Python, have v3.0 32bit installed on Windows 7, installed 
distribute, now trying to install pymysql and am getting the below error.  Any 
pointers on how to fix?  thanks!!  -Noah

[C:\Python32]pip install --upgrade distribute
Real name of requirement distribute is distribute
Requirement already up-to-date: distribute in c:\python32\lib\site-packages\dist
ribute-0.6.28-py3.2.egg
Cleaning up...

[C:\Python32]easy_install pymysql
Searching for pymysql
Reading http://pypi.python.org/simple/pymysql/
Couldn't find index page for 'pymysql' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
Reading http://pypi.python.org/simple/PyMySQL/
Reading http://code.google.com/p/pymysql
Best match: PyMySQL 0.5
Downloading http://pypi.python.org/packages/source/P/PyMySQL/PyMySQL-0.5.tar.gz#
md5=125e8a3449e05afcb04874a19673426b
Processing PyMySQL-0.5.tar.gz
error: Not a recognized archive type: c:\users\noahco~1\appdata\local\temp\easy_
install-gpekqc\PyMySQL-0.5.tar.gz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I verify if the content of a variable is a list or a string?

2012-01-31 Thread Noah Hall
On Wed, Feb 1, 2012 at 12:44 AM, Andres Soto  wrote:
> Hi,
> I'm writing a function which receive a list which elements are strings or
> new lists (sublists) containing strings.
> How can I verify if sone element of the list (which is contained in a
> variable) is a list or a string?
> I found the method isinstance(object,class) but I don't know which class
> should I use for.
> Thank you, regards
>
> Prof. Dr. Andrés Soto
> DES DACI
> UNACAR

"list" and "str"

>>> my_list = [1, 2, 3]
>>> isinstance(my_list, list)
True
>>> my_string = "foobar"
>>> isinstance(my_string, str)
True
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is this syntax ?

2011-06-19 Thread Noah Hall
On Sun, Jun 19, 2011 at 2:41 PM, candide  wrote:
> With Python 2.7 :
>
 x="foo"
 print '"'+x+'"'
> "foo"

> What is this curious syntax on line 2 ? Where is it documented ?

Just to make it clear to you what is happening -

>>> x = "foo"
>>> print ' " ' + x + ' " '
 " foo "
>>>

Anyway, it's documented here -
http://docs.python.org/tutorial/introduction.html#strings
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Better way to iterate over indices?

2011-06-21 Thread Noah Hall
On Tue, Jun 21, 2011 at 7:05 PM, Billy Mays  wrote:
> I have always found that iterating over the indices of a list/tuple is not
> very clean:
>
> for i in range(len(myList)):
>    doStuff(i, myList[i])

> I know I could use enumerate:
>
> for i, v in enumerate(myList):
>    doStuff(i, myList[i])
>
> ...but that stiff seems clunky.

You're not using it properly. Think about it. You're giving two names
- i and v. You've forgotten about v -

>>> for i, v in enumerate('fish'):
... print i, v
...
0 f
1 i
2 s
3 h


HTH.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what happens inside?

2011-06-22 Thread Noah Hall
On Wed, Jun 22, 2011 at 4:45 PM, Chetan Harjani
 wrote:
> why tuples are immutable whereas list are mutable?
Because an immutable data type was needed, and a mutable type was also needed ;)

> why when we do x=y where y is a list and then change a element in x, y
> changes too( but the same is not the case when we change the whole value in
> x ), whereas, in tuples when we change x, y is not affected and also we cant
> change each individual element in tuple. Someone please clarify.

That's because y points to an object. When you assign x = y, you say
"assign name x to object that's also pointed to by name y". When you
change the list using list methods, you're changing the actual object.
Since x and y both point to the same object, they both change.
However, if you then assign y = [1], name y no longer points to the
original object. x still remains pointing to the original object.

>>> a = [1,2] # assign name a to object [1,2]
>>> b = a # assign name b to object referred to by name a
>>> b
[1, 2]
>>> a = [3,4] # assign name a to object [3,4]
>>> b
[1, 2]
>>> a
[3, 4]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python 3 constant

2011-06-22 Thread Noah Hall
On Wed, Jun 22, 2011 at 7:54 PM, sidRo  wrote:
> How to declare a constant in python 3?

There aren't true constants in Python, but instead we use a standard
defined by PEP 8, which states constants are in all caps, for example,
PI = 3.14, as opposed to pi = 3.14 which could change (according to
PEP 8, that is)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Project-wide variable...

2011-06-23 Thread Noah Hall
On Thu, Jun 23, 2011 at 2:41 PM, Gnarlodious  wrote:
> Is there a way to declare a project-wide variable and use that in all
> downstream modules?

Well, the standard way you should do it is to use import to import a
certain variable - for example -

a.py -

x = 3


>>>from a import x
>>>x
3
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Project-wide variable...

2011-06-23 Thread Noah Hall
On Thu, Jun 23, 2011 at 3:09 PM, Gnarlodious  wrote:
> On Jun 23, 7:59 am, Noah Hall wrote:
>> >>>from a import x
>
> I'm doing that:
> import Module.Data as Data

Well, that's not quite the same. You're using Module.Data as Data - I
guess you've done this because you've realised that import Module
means you still have to write Module.Data every time. But the correct
way to is state exactly which function or object you want - for
example, from Module import Data. Simple, right? I mean, you almost
had it, but it seems like you've gotten a little confused with various
theories.


>
> However I end up doing it in every submodule, so it seems a little
> redundant. I wish I could load the variable in the parent program and
> have it be available in all submodules. Am I missing something?

Well, generally, if you've got a variable that you need in all your
sub-modules, the chances are that your code infrastructure needs a bit
of reordering (at least, that's what I find in my case). Without
seeing your code, though, I would find it hard to make a judgement on
what you need. Perhaps reading up on the documentation will help -
http://docs.python.org/tutorial/modules.html#packages

Noah.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Project-wide variable...

2011-06-23 Thread Noah Hall
On Thu, Jun 23, 2011 at 6:18 PM, Guillaume Martel-Genest
 wrote:
> On Jun 23, 9:41 am, Gnarlodious  wrote:
>> Is there a way to declare a project-wide variable and use that in all
>> downstream modules?
>>
> What about using an environment variable?

Yes, that's fine, but only if the data is suitable for it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reg: playing with the list

2011-06-24 Thread Noah Hall
On Fri, Jun 24, 2011 at 8:01 AM, kaustubh joshi  wrote:
> Hey all,
> I am new here and new to python too. In general new to programming .
> I was working on aproblem.
> and need some help.
> I have a list of numbers say [2,3,5,6,10,15]
> which all divide number 30.
> Now i have to reduce this list to the numbers which are prime in number.
> i.e.
> [2,3,5]
> can somebody suggest?

Well, you can use a built-in function called "filter" to create a list
containing only values that meet a certain need, for example, this
will filter out everything that is even and put it into a new list -
>>> numbers = [1,2,3,4]
>>> def is_even(n):
return n%2==0 # returns true if even, false if not.

>>> filter(is_even,numbers)
[2, 4]


All you need to do is to create or adapt an algorithm that tests
whether a number is prime or not, and use that along with filter on
your list of numbers. Several examples exist, it's quite a popular
question.

HTH.

Noah.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3 syntax error question

2011-06-26 Thread Noah Hall
On Sun, Jun 26, 2011 at 2:04 PM, rzed  wrote:
> I've tried to install PySVG in a Python 3 setting, and I get a few
> errors on the build. Most are easy to fix, but this one I can't
> explain or fix:
>
> 
> Traceback (most recent call last):
>  File "", line 1, in 
>  File "builders.py", line 12, in 
>    from pysvg.shape import *
>  File "C:\Python32\lib\site-packages\pysvg\shape.py", line 91
>    def moveToPoint(self,(x,y)):
>                         ^
> SyntaxError: invalid syntax
> 
>
> The moveToPoint method occurs three times in the file, with identical
> signatures. The other two are not showing up as errors, though since
> they occur later in the file, that may not be indicative.
>
> I don't see anything erroneous in this line. The syntax error often
> comes from the previous line, but I've moved this method around and
> it has always failed on this line and no other, regardless of what
> went before.
>
> I'm new to Py3, so maybe there's some obvious thing I'm not seeing
> here. Does anyone have any suggestions?

Did you run it through 2to3? When I run
def a(b, (c,d)):
pass
through 2to3, it tells me what I need to change.

-def a(b, (c,d)):
+def a(b, xxx_todo_changeme):
+(c,d) = xxx_todo_changeme

(which is what Steven said)

If you haven't used 2to3, I suggest you use it.

HTH.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3 syntax error question

2011-06-26 Thread Noah Hall
On Sun, Jun 26, 2011 at 4:28 PM, rzed  wrote:
> steve+comp.lang.pyt...@pearwood.info wrote in
> news:4e074768$0$29982$c3e8da3$54964...@news.astraweb.com:
>
>> rzed wrote:
>>
>>> I've tried to install PySVG in a Python 3 setting, and I get a
>>> few errors on the build. Most are easy to fix, but this one I
>>> can't explain or fix:
>>>
>>> 
>>> Traceback (most recent call last):
>>>   File "", line 1, in 
>>>   File "builders.py", line 12, in 
>>>     from pysvg.shape import *
>>>   File "C:\Python32\lib\site-packages\pysvg\shape.py", line 91
>>>     def moveToPoint(self,(x,y)):
>>>                          ^
>>> SyntaxError: invalid syntax
>>> 
>>
>> Function signatures with automatic tuple-unpacking are no longer
>> allowed in Python3. So functions or methods like this:
>>
>> def moveToPoint(self,(x,y)):
>>
>> have to be re-written with the tuple unpacking moved into the
>> body of the function, e.g. something like this:
>>
>> def moveToPoint(self, x_y):
>>     x, y = x_y
>>
>>
>> Are you aware that you're trying to install a Python2 library
>> under Python3?
>>
>>
>
> Thank you all for your responses. Yes, I am aware of the version
> difference, but not of all the implications of that. I will run this
> through 2to3, but even without doing that, there are only about four
> syntax errors, and the others were obvious and easily corrected.
>
> There does not seem to be a Py3 version of this package. I was hoping
> to try it to see what broke. Well, I found out at least part of that,
> didn't I?
>
> I was not aware of the removal of tuple-unpacking. I expect there was
> some extensive conversation about that.
>
> As to 2to3, I have to say that:
>
> -def a(b, (c,d)):
> +def a(b, xxx_todo_changeme):
> +    (c,d) = xxx_todo_changeme
>
> ... is not terribly revealing if one is unaware of what about it
> needs changing. I know, I know: RTFM

It means delete every line with a '-' and replace them with those next
to the '+'
Of course, if you read the doc, it'll give you lots of different
options, including writing to the file, so all you need to do is
change the variable names.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Default value for optional parameters unexpected behaviour?

2011-06-26 Thread Noah Hall
On Sun, Jun 26, 2011 at 7:28 PM, Marc Aymerich  wrote:
> Hi,
> I'm trying to define a function that has an optional parameter which
> should be an empty list whenever it isn't given. However, it takes as
> value the same value as the last time the function was executed. What
> is the reason of this behaviour? How does python deal with default
> values (i.e. when are they assigned/created)?
>
> Thanks :)
>
 def a(foo=[]):
> ...  foo.append(1)
> ...  print foo
> ...
 a()
> [1]
 a()
> [1, 1]
 a()
> [1, 1, 1]
 a()
> [1, 1, 1, 1]
 a()
> [1, 1, 1, 1, 1]
 a()
> [1, 1, 1, 1, 1, 1]

Your problem arises because lists are mutable. Because foo (by
default, initially) points to a given list, every time the function is
called, it uses the same list that foo was first pointed to, if the
default argument value is taken.
The way to fix this is to instead do -

def a(foo=None):
if foo is None:
foo = []
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python basic program problem

2011-06-27 Thread Noah Hall
On Mon, Jun 27, 2011 at 8:05 AM, Amaninder Singh  wrote:
> Hi,
> I am fairly new to python, I am trying to write simple code and It is
> giving me syntax error. I am reading a book and following the
> directions as it says in the book but I am not sure why it is not
> working. Please guide me through. Any help appreciated.
 x = 2
 if x == 2:
>   print "This is a test"
>
> SyntaxError: invalid syntax
 if x == 2:
>           print "This is a test"
>
> SyntaxError: invalid syntax
 x = 2
 if x = 2:
>
> SyntaxError: invalid syntax
 if x == 2:
>        print "This is test"
>
> SyntaxError: invalid syntax
 Type "copyright", "credits" or "license()" for more information.
> SyntaxError: invalid syntax


 print "this is a test"
> SyntaxError: invalid syntax
 import keyword
 print keyword.kwlist
> SyntaxError: invalid syntax
 print "hellow world"
> SyntaxError: invalid syntax
 print 'hellow world'
> SyntaxError: invalid syntax

Looks like you're using the 3.x version, while your guide is 2.x. I
suggest you download the 2.x version, or find a new tutorial.

HTH
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python basic program problem

2011-06-27 Thread Noah Hall
On Mon, Jun 27, 2011 at 11:18 PM, Amaninder Singh  wrote:
> Yes, I think I am using 3.0 version. So how much difference is in between 
> these two?
> On Jun 26, 2011, at 11:18 PM, Noah Hall wrote:
>> On Mon, Jun 27, 2011 at 8:05 AM, Amaninder Singh  
>> wrote:
>>> Hi,
>>> I am fairly new to python, I am trying to write simple code and It is
>>> giving me syntax error. I am reading a book and following the
>>> directions as it says in the book but I am not sure why it is not
>>> working. Please guide me through. Any help appreciated.
>> Looks like you're using the 3.x version, while your guide is 2.x. I
>> suggest you download the 2.x version, or find a new tutorial.


Well, quite a lot. Read this -
http://wiki.python.org/moin/Python2orPython3 to get a better picture.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suppressing newline writing to file after variable

2011-06-28 Thread Noah Hall
On Tue, Jun 28, 2011 at 5:05 PM, Ellerbee, Edward  wrote:
> Hi all, newbie question here. I'm using python 2.7. I've built my first
> program to pull some info off the web, process it, and build dialpeers for a
> cisco router. I have 2 problems - the first is the formatting of printing
> the gathered information to a file. It seems to be inserting a new line
> after the variable is written. I've searched the web, but unsure of which
> method could fix this issue.
>
> Here is my code snippet:
>
> count=0
> o = open('dialpeers.txt', 'w')
> for line in open('final.txt', 'r'):
>     figureDpn = count + 1000

>     dpn = str(figureDpn)
>     label = "dial-peer voice " + dpn
>     o.write(label)
>     o.write('\n')
>     destpatt = "destination-pattern " + line + ""

Try line.rstrip() instead. It'll remove all newlines. Also, I suggest
you use string formatting, for example,
>>>destpatt = "destination-pattern %s" % line.rstrip()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suppressing newline writing to file after variable

2011-06-28 Thread Noah Hall
On Tue, Jun 28, 2011 at 6:32 PM, Ellerbee, Edward  wrote:
> Thank you!
>
> That works perfect, I'll have to look into string formatting more.
>
> My next issue to solve I've been researching is:
>
> How to condense a group of numbers to a wildcard list. For example:
>
> 252205
> 252206
> 252208
> 252220
> 252221
> 25
> 252223
> 919745
> 919725
> 919785
> 704770 thru 704799 (all numbers listed individually in a file)
>
> Condense to:
> 25220[568]
> 25222[0-3] (or 25222[0123] is fine too)
> 9197[248]5
> 7047[0-9][0-9]
>
> Any recommendations on where to start, a method or function to research?

Hm, perhaps re (http://docs.python.org/library/re.html). It depends on
whether it's a standard static set of values you need to compare
against, or a undefined dynamic set.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is the Usenet to mailing list gateway borked?

2011-06-29 Thread Noah Hall
On Wed, Jun 29, 2011 at 9:34 PM, Andrew Berg  wrote:
> I didn't get at least two messages from the "call a function every 10
> seconds thread", and possibly some other messages, and I access the
> group via the mailing list. I use the latest stable Thunderbird, if that
> matters. I've only noticed this recently, and I'm still getting other
> messages. In fact, I only noticed this because I got a message that
> referenced messages I didn't get.

I think the more likely answer is that it was sent without being also
sent to python-list.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: learn the network program of python

2011-03-04 Thread Noah Hall
On Fri, Mar 4, 2011 at 12:47 PM, loopzhong001  wrote:
> Dear All,
>     Would anyone tell me haow to start?


Well, to start on this mailing list - 1) Name the networking
framework/modules you want to use (if you have one, else say "can
someone suggest a networking framework/module?") 2) Say what you want
to do with it and 3) State how much programming you've done in Python
already.

;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How Translate This PHP

2011-03-06 Thread Noah Hall
On Sun, Mar 6, 2011 at 2:45 PM, Victor Subervi  wrote:
> Hi;
> How do I translate this PHP code?
>
> if($ok){
>     echo "returnValue=1";
> }else{
>     echo "returnValue=0";
> }

>From the code provided -

if ok:
print 'returnValue=1'
else:
print 'returnValue=0'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How Translate This PHP

2011-03-06 Thread Noah Hall
On Sun, Mar 6, 2011 at 3:11 PM, Victor Subervi  wrote:
> Ah. I thought I had to "return" something!

Well, based on what you asked, you would've, but based on the code,
all it was doing is printing "returnValue - value"

Of course, a better way of doing it would be to use formatting -

For example,

print 'returnValue=%d' % ok
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some Minor questions on Class and Functions

2011-03-20 Thread Noah Hall
> class Message:
>    def __init__(self,string1,string2,lenstr1,lenstr2):
>        self.string1="MY"
>        self.string2="NAME"
>        self.lenstr1=lenstr1
>        self.lenstr2=lenstr2

The variables string1 and string2 that you're passing here are in fact
useless. They don't do anything inside the method. Is there any point
for them? There's no need to pass __init__ variables just so you can
assign self.variable_name = "fixed text".

>    def lenstring(self):
>        lenstr1=len(self.string1)
>        lenstr2=len(self.string2)

I think you want self.lenstr1 and self.lenstr2 here - otherwise you're
assigning local variables with the same name as those defined within
the class, and throwing them away.

>    def printstr(self):
>        print lenstr1
>        print lenstr2

Again, I think you want self.lenstr1 and self.lenstr2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Free Software University - Python Certificate

2011-03-22 Thread Noah Hall
On Tue, Mar 22, 2011 at 11:30 AM, Giovani  wrote:
>> I don't know whether this site is useful or not.
>>
>> Assuming this site is serious:
>> If you are already subscribed you might be able to give some feedback.
>>
>> One can't even see the list of courses without regsitering.
>> This is very unprofessional and might indicate, that they just want to
>> reap contact information.
>
> I'm not the admin of the site, when the course finish will be aviable
> throgh the main website (I think).
>
>>
>> One can't even see a date or a time line without registering. So one
>> doesn't even know whether the whole project is already dead for several
>> years or really active.
>>
>
> I really active, there more than 100 users registered and lots of them
> are working to make several course certificates (PHP, Python, Java,
> JavaScript, FreeNAS, etc..).
>
>> To me all this does not look professional for somebody who want to
>> attract students / instructors
>
> The finally is make professional contents, but this project is already
> in a early stage.


I've been following this project for a while, since it was annouced on
the Ubuntu forums. I can't say that I've been at all impressed by
anything they have to offer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python-list Digest, Vol 152, Issue 40

2016-05-26 Thread Noah Fleiszig
thank you

On Thu, May 26, 2016 at 2:00 AM,  wrote:

> Send Python-list mailing list submissions to
> python-list@python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
> https://mail.python.org/mailman/listinfo/python-list
> or, via email, send a message with subject or body 'help' to
> python-list-requ...@python.org
>
> You can reach the person managing the list at
> python-list-ow...@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. html & python connection problem with hyperlinks
>   (litssa2...@gmail.com)
>2. Re: Exended ASCII and code pages [was Re: for / while else
>   doesn't make sense] (Chris Angelico)
>3. Re: for / while else doesn't make sense (Marko Rauhamaa)
>4. Re: Spurious issue in CPython 2.7.5 (thomas povtal.org)
>5. Re: Spurious issue in CPython 2.7.5 (Tim Golden)
>6. Re: for / while else doesn't make sense (Christopher Reimer)
>7. Re: Spurious issue in CPython 2.7.5 (thomas povtal.org)
>8. ValueError: I/O operation on closed file (San)
>9. Re: ValueError: I/O operation on closed file (Joel Goldstick)
>   10. Find the max number of elements in lists as value in a
>   dictionary (Daiyue Weng)
>   11. Re: ValueError: I/O operation on closed file (alister)
>   12. IndexError for using pandas dataframe values (Daiyue Weng)
>   13. Re: Find the max number of elements in lists as value in a
>   dictionary (Jussi Piitulainen)
>   14. Re: Find the max number of elements in lists as value in a
>   dictionary (Jon Ribbens)
>   15. Re: html & python connection problem with hyperlinks
>   (justin walters)
>
>
> -- Forwarded message --
> From: litssa2...@gmail.com
> To: python-list@python.org
> Cc:
> Date: Wed, 25 May 2016 03:24:30 -0700 (PDT)
> Subject: html & python connection problem with hyperlinks
> Why not created the field title, that located on the template
> BusinessList.html as a link to go to Business_Detail.html..? please check
>
> Code:
>
> models. py:
>
> from django.db import models
>
>
> REGIONS = (
> ('ΘΕΣ', 'ΘΕΣΣΑΛΟΝΙΚΗ'),
> ('ΣΕΡ', 'ΣΕΡΡΕΣ'),
> ( 'ΑΘΗ', 'ΑΘΗΝΑ'),
>
>
>
> TYPEOFBUSINESS = (
> ('ΕΣΤ', 'ΕΣΤΙΑΤΟΡΙΑ'),
> ('ΦΑΡ', 'ΦΑΡΜΑΚΕΙΑ'),
> ('ΒΙΒ', 'ΒΙΒΛΙΟΠΩΛΕΙΑ'),
> ( 'ΚΟΜ', 'ΚΟΜΜΩΤΗΡΙΑ'),
> ('ΣΙΝ', 'ΣΙΝΕΜΑ')
>
> )
>
> class Business(models.Model):
> created_Date = models.DateTimeField(auto_now_add=True)
> owner = models.ForeignKey('auth.User', related_name='snippets', null=True)
> title = models.CharField(max_length=100, blank=True, default='')
> Type_of_Business = models.CharField(max_length=3, choices=TYPEOFBUSINESS)
> region = models.CharField(max_length=3, choices=REGIONS)
> address = models.CharField(max_length=100, blank=True, default='')
> phone = models.CharField(max_length=15, blank=True, default='')
> image = models.ImageField(null=True)
>
>
> def __str__(self):
> return str(self.title)
>
> views.py
>
> from django.contrib.auth.models import User
> from django.http import HttpResponse
> from django.shortcuts import render, get_object_or_404
> from rest_framework import filters
> from rest_framework import generics
> from rest_framework import permissions
> from snippets.permissions import IsOwnerOrReadOnly
> from snippets.serializers import SnippetSerializer
> from snippets.serializers import UserSerializer
> from .models import Business
>
>
>
> class UserList(generics.ListAPIView):
> queryset = User.objects.all()
> serializer_class = UserSerializer
>
>
> class UserDetail(generics.RetrieveAPIView):
> queryset = User.objects.all()
> serializer_class = UserSerializer
>
> class BusinessList(generics.ListCreateAPIView):
>
> permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
> queryset = Business.objects.all()
> serializer_class = SnippetSerializer
> filter_backends = (filters.DjangoFilterBackend,filters.SearchFilter,
> filters.OrderingFilter,)
> filter_fields = ('Type_of_Business', 'region')
> search_fields = ('Type_of_Business', 'region')
> ordering_fields = ('Type_of_Business','title', 'region')
>
>
> def BusinessList(request):
> business = Business.objects.all();
> return render(request, 'snippets/BusinessList.html' {'business':business})
>
> def perform_create(self, serializer):
> serializer.save(owner=self.request.user)
>
>
>
> class Business_Detail(generics.RetrieveUpdateDestroyAPIView):
> permission_classes = (permissions.IsAuthenticatedOrReadOnly,
> IsOwnerOrReadOnly,)
> queryset = Business.objects.all()
> serializer_class = SnippetSerializer
>
>
> def Business_Detail(request, pk):
> business = get_object_or_404(Business, pk=pk)
> return render(request, 'snippets/Business_Detail.html', {'business':
> business})
>
> serializers.py
>
> from rest_framework import serializers
> from snippets.models import Business
> from django.contrib.auth.models import User
>
>
> class SnippetSerializer(serializers.HyperlinkedModelSerializer):
> o

[no subject]

2016-05-27 Thread Noah Fleiszig
Thank you

-- 
Sent from Gmail Mobile
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python-list Digest, Vol 152, Issue 43

2016-05-28 Thread Noah Fleiszig
Thank you and ok

-- 
Sent from Gmail Mobile
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Jargons of Info Tech industry

2005-10-22 Thread noah bedford
On Wed, 12 Oct 2005 21:50:22 GMT
Roedy Green <[EMAIL PROTECTED]> wrote:

>It is almost like providing ladders and setting out cookies and milk
>for the burglars.

Fire escapes at christmas.
-- 
http://mail.python.org/mailman/listinfo/python-list


OT: loop help

2005-11-24 Thread noah bedford
On Thu, 27 Oct 2005 07:00:34 GMT
Gorlon the Impossible <[EMAIL PROTECTED]> wrote:

>I am using Python 2.3.5 with IDLE 1.0.5 on a Windows98 PC.

Just had to say it... 

MicroSoft makes PCs now?


-\n


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [pydotorg-www] www.python.org - Backend is unhealthy

2015-05-08 Thread Noah Kantrowitz

On May 8, 2015, at 10:28 AM, Chris Angelico  wrote:

> On Fri, May 8, 2015 at 6:17 PM,   wrote:
>> I cannot access www.python.org.
>> I always get
>> 
>> Error 503 Backend is unhealthy
>> 
>> Backend is unhealthy
>> 
>> Guru Mediation:
>> 
>> Details: cache-ams4149-AMS 1431072956 2041303800
>> 
>> Varnish cache server
>> 
>> 
>> Is it only me?
>> 
> 
> No, it's not only you. I get the same but with different details:
> 
> Details: cache-syd1627-SYD 1431073575 864283876
> 
> It looks to me as if my result is coming from a cache node in Sydney;
> yours is coming from some other cache node, so it's not just one node
> that's down.
> 
> Cc'ing in the www list in case someone there knows, and I'll create a
> github issue to ping the people there.

Should be recovering now.

--Noah



signature.asc
Description: Message signed with OpenPGP using GPGMail
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 1/2 evaluates to 0

2011-10-12 Thread Noah Hall
On Wed, Oct 12, 2011 at 11:14 AM, Laurent Claessens  wrote:
> This is well known :
>
 1/2
> 0
>
> This is because the division is an "integer division".
>
> My question is : how can I evaluate 1/2 to 0.5 ? Is there some non integer

Include from __future__ import division on the top of your file

>>> from __future__ import division
>>> 1/2
0.5
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 1/2 evaluates to 0

2011-10-12 Thread Noah Hall
On Wed, Oct 12, 2011 at 12:28 PM, Laurent  wrote:
>
>> Include from __future__ import division on the top of your file
>>
>  from __future__ import division
>  1/2
>>
>> 0.5
>>
>
> Wohaw. This means that this behavior is going to be default in a foreseeable
> future ?

Never in Python 2.x, but it already is in Python 3.x [1]

[1] - http://www.python.org/dev/peps/pep-0238/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if object is an integer?

2011-10-17 Thread Noah Hall
On Sat, Oct 15, 2011 at 12:44 AM, MrPink  wrote:
>
> Is there a function in Python that can be used to test if the value in
> a string is an integer?  I had to make one up for myself and it looks
> like this:
>
> def isInt(s):
>    try:
>        i = int(s)
>        return True
>    except ValueError:
>        return False


There's the isdigit method, for example -

>>> str = "1324325"
>>> str.isdigit()
True
>>> str = "1232.34"
>>> str.isdigit()
False
>>> str = "I am a string, not an int!"
>>> str.isdigit()
False
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return of an old friend

2011-11-25 Thread Noah Hall
On Fri, Nov 25, 2011 at 5:08 AM, Matt Joiner  wrote:
> I haven't heard of you before, but feel like I've missed out on something.
>
> Do you (or someone else) care to link to some of your more contentious work?

Ignore him, he's a troll with an unjustly inflated ego.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please explain this for me

2011-12-20 Thread Noah Hall
On Wed, Dec 21, 2011 at 4:39 AM, Emeka  wrote:
>
> Hello All,

> v = []
>
> def add_to_list(plist):
>     u = plist.append(90)
>     return u
>
> add_to_list(v)  # This function call returns nothing
> Could someone explain why this function call will return nothing?

It's because add_to_list returns the value returned from plist.append
stored in u.
append changes a list in place and returns nothing. Functions that
return nothing return None. This is why it'll be None - u is None
because append returns None.


> add_to_list([])
> This one returns nothing, why?

It's because the object [] here has no name, so that you have no way
to refer to it after the function changes it, since it changes it in
place. It gets eaten by Python, never to be seen again.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Zealotry [was Re: how to install lxml in window xp?]

2012-01-12 Thread Noah Hall
On Fri, Jan 13, 2012 at 5:47 AM, alex23  wrote:
> On Jan 13, 3:02 pm, Steven D'Aprano  +comp.lang.pyt...@pearwood.info> wrote:
>> Why is it that only Linux and Mac users are accused of being "zealots"?
>
> Incidentally, in the post I replied to, Tamer was talking about
> Windows 7, so there's that too.

I agree with what you posted.

If there was a single bad thing I would point out to anyone about the
Python community, it would be that there are a huge amount of
"freetards" - people who believe that Linux is the only way, or that
Linux is the best way. Protip: It's not the only way, and it's not
always the best way.

Use what works for you. If Windows works for you, great. Same applies
to every OS. It's not then unreasonable to ask others for support for
that OS - they may not have the ability to provide support, but it's
always good to ask. If you have no choice in the matter, sucks to be
you, but live with it. Worse things have happened than having to use
Windows XP, as much as I *personally* dislike XP.

Claiming that x OS is best, and that every other OS is rubbish is
insane. Different operating systems do things differently, and are
therefore suited for different tasks and for different people.

Suggesting to someone that doing a task is easier on a different OS -
"Yeah, I can't help you but I might I suggest you do Python
development on Linux - these sort of problems are much easier to
handle when you have a package manager system and Linux distros have
awesome Python support"  is fine and perfectly sensible - "USE LINUX
OMFG!111!! YOU'RE SO LAME, WINDOZE SUCKS OMFG YOU N00B! I'M SO COOL
USE MY HARDCORE GENTOO INSTALL THAT TOOK 36 HOURS AND SHAVED 2 SECONDS
OFF MY BOOTUP TIME! LOOK AT THE SPINY COMPIZ CUBE! I DON'T KNOW WHAT I
DID BEFORE I COULD MAKE MY DESKTOP CUBE-Y!", as in the post you
referred to, is not.

I see this kind of nonsense everywhere, but it tends to be in the
Linux and Apple community more - I've no idea why, probably has
something to do with being a minority.

For reference, I am a Linux developer who uses Windows, Linux, *BSD
and OS X, each in a place where it's suitable.

tl;dr - Use what works for you. Suggest, don't preach.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Zealotry [was Re: how to install lxml in window xp?] (OT)

2012-01-13 Thread Noah Hall
On Fri, Jan 13, 2012 at 7:54 AM, Stefan Behnel  wrote:
> Noah Hall, 13.01.2012 08:29:
>> I'M SO COOL
>> USE MY HARDCORE GENTOO INSTALL THAT TOOK 36 HOURS AND SHAVED 2 SECONDS
>> OFF MY BOOTUP TIME
>
> Just an off-topic thing that your comment above reminded me of: has anyone
> ever noticed that there are even quick install guides for Gentoo Linux?

Gentoo Linux - for when life's just too simple.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Zealotry [was Re: how to install lxml in window xp?]

2012-01-13 Thread Noah Hall
On Fri, Jan 13, 2012 at 8:07 PM, Tamer Higazi  wrote:
> dear people!
> I have just opened my MTU client, and figured out that through my
> comment, i caused a complete NONSENSE discussion at all.
>
>
> 1. I am not a zealot or whatever. I code on Linux and port it on MAC and
> WINDOWS. I do write solutions for customers across the whole 3 platform,
> and mostly I succeed because I have to figure out in advance which
> software (packages) are being supported and how far.

> Use Linux!
> Specially Gentoo Linux!

Screams zealot to me. If not, certainly not a very useful reply.

"Hey guys, I want to cut the bread, can someone tell me how to use the knife?"

"Use a futuristic laser! Build it yourself for the uber 1337 status!"

> 2. There are many open source projects out (don't ask where, look for
> yourself, you are old enough!) as well commercial software vendors who
> don't offer their products, or give support for Windows XP.

More fool them; XP is still (unfortunately) heavily used in workplaces
and in Universities. Luckily, Windows, unlike Linux, is largely
backwards compatible - it's rare to find a program which won't run on
XP if it can run on Vista+, unless it's a game that relies on DX11 or
something.

> 3. All of you know, that windows xp is by Microsoft not anymore
> supported. Neither with Security Updated, Enhancements with Software,
> SDK or whatever. and not only XP, also Win95,98,ME, and 2000
> Professional (not the server editions).

Mainstream support ended, yes, but extended support lasts until 2014.
Extended support is security updates and the like.
http://support.microsoft.com/lifecycle/?C2=1173

> 4. Of course any OS has it's advantages and disadvantages. Gentoo is a
> rolling distribution, when it's set up it works nicely. Of course, you
> have to invest a lot of effort to get in what doesn't mean that Debian
> and Ubuntu, and the others are worse.

Yeah, no. I prefer an operating system that's stable and secure for my
servers and for my development. Call me crazy, but I like to get work
done.

> >From my personal point of view, I will never set up a gentoo machine as
> a server in a datacenter, I would rather use BSD Unix. But this is
> something that personally everybody has to decide for him/herself.

Good boy you! I'm glad you've got some sense, there.

> Now, I hope that I put a line under this discussions and beg the kids
> between the age of 18 - 24 who are really impulsive to fire around with
> the guns on others to stop this nonsense thread.
>
> That doesn't leave a nice picture in the community.

Hate to break it to you, but you started it with

> Use Linux!
> Specially Gentoo Linux!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Zealotry [was Re: how to install lxml in window xp?]

2012-01-14 Thread Noah Hall
On Sat, Jan 14, 2012 at 2:39 AM, Terry Reedy  wrote:
> On 1/13/2012 3:42 PM, Noah Hall wrote:
>>
>> On Fri, Jan 13, 2012 at 8:07 PM, Tamer Higazi
>>  wrote:
>>>
>>> dear people!
>>> I have just opened my MTU client, and figured out that through my
>>> comment, i caused a complete NONSENSE discussion at all.
>
>
>>> 1. I am not a zealot or whatever. I code on Linux and port it on MAC and
>>> WINDOWS. I do write solutions for customers across the whole 3 platform,
>>> and mostly I succeed because I have to figure out in advance which
>>> software (packages) are being supported and how far.
>
>
>>> Use Linux!
>>> Specially Gentoo Linux!
>>
>>
>> Screams zealot to me. If not, certainly not a very useful reply.
>
>
> Noah, those last two lines you quoted are NOT in the post you are quoting.
> Perhaps Tamer said them previously. If so, you should say so: "In a previous
> post, you said...". Otherwise, it looks like you made those up and put words
> in his pen.

Good point. In a previous post, that started all this, he said

> Use Linux!
> Specially Gentoo Linux!

when replying to someone who asked

> how can i install the lxml  in my xp??
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >