Re: [Tutor] trouble with stringio function in python 3.2

2015-05-04 Thread Chris Warrick
On Mon, May 4, 2015 at 7:03 AM, anupama srinivas murthy
 wrote:
> Hello,
>
> My python code needs to run on versions 2.7 to 3.4. To use stringio
> function as appropriate, the code i use is;
>
> if sys.version < '3':

A better comparison to use would be

if sys.version_info[0] == 2:

It’s the standard idiom, which compares 2 == 2 instead of '2.7.9 (more
garbage here)' < '3'.

> dictionary = io.StringIO(u"""\n""".join(english_words))
> else:
> dictionary = io.StringIO("""\n""".join(english_words))
>
> The code runs fine on all versions mentioned above except for 3.2 where i
> get the error:
> dictionary = io.StringIO(u"""\n""".join(english_words))
> ^
> SyntaxError: invalid syntax
>
> How can I solve the issue?

The best solution is not supporting Python 3.2, especially considering
that Python 3.3.0 was released in September 2012 (and the latest
version is 3.4.3).

Python 3.0–3.2 do not support the u'' notation for Unicode strings, it
was restored in Python 3.3 to make it easier to write code compatible
with 2.x and 3.x (just like you are trying to do here!)  Python has to
read in and parse all the code, and it encounters a strange u'' thing
it does not recognize.  Thus, it fails with a SyntaxError.

Many Python projects out there don’t support 3.2, and this was one of
the reasons.

If you REALLY have to support it (why?), there are two solutions.  The
first one is to use '\n'.decode('utf-8') instead of u'\n' for Python
2.7, which will not trigger a compile error (it does not matter that
there is no str.decode in Python 3, the syntax makes sense even if it
cannot be executed).  The second one is to use (at the top of your
file)

from __future__ import unicode_literals

This will make Python 2.7 think '\n' is a Unicode string, and Python
3.x will ignore this line — in that case, you can even drop the
if/else and just use the same dictionary assignment for both Pythons.
Just be warned that it applies to the entire file and can lead to
problems.

PS. There is no reason to use """multi-line strings""" in this case,
regular "strings" will do it equally well and are more readable.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python application with same name as its corresponding project

2015-07-31 Thread Chris Warrick
On 31 July 2015 at 17:13, Anthony DuPont  wrote:
> I am trying to setup my python application in a more standard way. In my
> research, the general recommendation seems to be that if my application is
> called projectgendocs, here is an acceptable structure:
>
> ProjectParent
> |-- bin/
> |  |-- projectgendocs.py
> |
> |-- projectgendocs
> |  |-- unittest
> |  |  |-- __init__.py
> |  |  |-- test_main.py
> |  |
> |  |-- __init__.py
> |  |-- main.py
> |
> |-- setup.py
> |-- README
>
>
> It is my understanding that ProjectParent would be added to the PYTHONPATH
> so the projectgendocs project could be discovered for importing. The
> problem I am encountering is that when the bin/projectgendocs.py is run, it
> breaks the imports in the ProjectParent/projectgendocs files that have
>
> import projectgendocs.somefile.py
>
> I discovered this is due to the fact that the bin/projectgendocs is
> discovered in the search for a package called projectgendocs because the
> bin directory is added to the search path. I verified this by renaming the
> bin/projectgendocs.py file to something different. So, my question is this:
> How can a python application (the file installed in the bin folder) have
> the same name as its corresponding python project and not break the
> absolute imports? Or is the only way to do this is by using relative
> imports?
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

Don’t create custom bin/ scripts, use setuptools entry points. I
described it on my blog:

https://chriswarrick.com/blog/2014/09/15/python-apps-the-right-way-entry_points-and-scripts/

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] generate a list/dict with a dynamic name..

2015-09-27 Thread Chris Warrick
On 27 September 2015 at 18:38, bruce  wrote:
> Hi.
>
> I can do a basic
>  a=[]
> to generate a simple list..
>
> i can do a a="aa"+bb"
>
> how can i do a
>  a=[]
>
> where a would have the value of "aabb"
>
> in other words, generate a list/dict with a dynamically generated name
>
> IRC replies have been "don't do it".. or it's bad.. but no one has
> said you can do it this way..
>
> just curious..
>
> thanks
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

And we really mean it.

There are two ways.  One involves e**l, which means you are executing
arbitrary code, and if a contained some malicious code, it could break
your system.  Using e**l is considered bad for this precise reason:
you don’t know if the input might lead to formatting your hard drive.
And you should not trust it to be good.

The other way involves modifying the g*s() dict.  It does not
always work though.

But for a REAL way to do it, just create a dict and use it — you can
have arbitrary variable names just fine:

things = {}
a = "aabb"
things[a] = []

PS. why are you creating a out of two strings?  Why not just a = "aabb"?

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] command line list arguments

2015-11-07 Thread Chris Warrick
On 7 November 2015 at 02:56, Garry Willgoose
 wrote:
> I want to input a python list as a command line argument as for example
>
> python weathering-sens.py -daughter ['p0-50-50','p0-0-0-100’]
>
> but what I get from sys.argv is [p0-50-50,p0-0-0-100] without the string 
> delimiters on the list elements. I’m probably missing something really simple 
> because sys.argv returns strings and probably strips the string delimiters in 
> that conversion … but is there any way that I can keep the string delimiters 
> so that inside the code I can just go (if arg is ['p0-50-50','p0-0-0-100’])
>
> a=eval(arg)
>
> or is there no alternative to doing this
>
> python weathering-sens.py -daughter 'p0-50-50’ 'p0-0-0-100’
>
> and doing the legwork of interpreting all the arguments individually (I’ve 
> seen an example of this on the web).

1. NEVER use eval().
2. Trying to pass Python code as arguments looks bad.  Don’t do that.
3. Your issues with '' are caused by your shell. You would need to
wrap your entire thing in quotes first, or use escaping. But instead,
4. Use argparse or another argument parsing solution, and implement it
with two arguments.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Debugging in Python

2015-11-16 Thread Chris Warrick
On 16 November 2015 at 15:43, Alan Gauld  wrote:
> Thats not an IDE its just a raw interpreter.
> IDLE is a full IDE that includes a debugger.

It’s an awful piece of garbage that pretends to be an IDE.

>> I encountered some error in the source , then I fixed it and tried to run
>> the module with the above snippet again , but the the error prevails even
>> though the error part is commented and the updated version saved.
>
>
> You need to reload the module but sadly there is no simple command to do
> that in the interpreter. There is in IDLE ("Restart Shell" menu item)
>
> So if you use IDLE your issues will be resolved. You can install
> IDLE3 from the Ubuntu package manager.

No, they won’t. They will be replaced by a much worse and less
friendly IDE. Please don’t bother installing IDLE and use the normal
`python3` shell, ipython or bpython.

The correct fix is to exit() from the python3 shell and start it again.
Alternatively, add some main code at the end of your file and use
`python3 hlibert.py`:

if __name__ == '__main__':
hilbert(3)

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] To FORMAT or not to

2016-01-03 Thread Chris Warrick
On 3 January 2016 at 13:27, yehudak .  wrote:
> Hi there,
> In a program I wrote the following line (Python 3.5):
>
> print("You've visited", island, '&', new + ".")
>
> A programmer told me that it's a bad habit, and I should have used instead:
>
> print("You've visited {0} {1} {2}{3}".format(island, "&", new, "."))
>
> May I understand why?
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

The programmer was not very intelligent in his use of str.format in
the first place. A more sensible way to write this is:

print("You've visited {0} & {1}.".format(island, new))

Formatting with constant strings is pointless, just include it in the
original input. However, string formatting is not.

Here are a couple of reasons:
* String formatting works everywhere, but this syntax is specific to
print() — if you use something else, you might end up producing faulty
code
* The corrected string formatting usage is more readable than the
original print()
* String concatenation with + requires that all arguments are strings,
which is even less readable
* With string formatting, you can apply special formatting to your
inputs (eg. set width, number precision…), which is hard or impossible
with print()
* Using print() with commas adds spaces between all entries, which
might look bad (and it does in this example); the only way to prevent
that is by setting `sep=`, but then you need to remember about a space
after "visited" and around the ampersand…
* Easy to localize (translate into different languages), which is
generally impossible with any of the other options (some languages
might rearrange the sentence!)

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] idle??

2016-01-09 Thread Chris Warrick
On 8 January 2016 at 20:07, bruce  wrote:
> Hey guys/gals - list readers
>
> Recently came across someone here mentioning IDLE!! -- not knowing
> this. I hit google for a look.
>
> Is IDLE essentially an ide for doing py dev? I see there's a
> windows/linux (rpms) for it.
>
> I'm running py.. I normally do $$python to pop up the py env for quick
> tests.. and of course run my test scripts/apps from the cmdline via
> ./foo.py...
>
> So, where does IDLE fit into this

IDLE is a sad little “IDE”, which is really ugly, because it’s written
in Tk. It lacks many IDE features. It comes with a really basic
debugger (that doesn’t even highlight the line that is being currently
executed…), function signature hinting, and some code completion.

And it doesn’t even do something as basic as line numbering.

Pretty much anything is better than IDLE. I recommend using vim with
the python-mode plugin and YouCompleteMe. The Atom editor can also be
a good Python environment. For fans of full-blown IDEs, there’s
PyCharm.

For experiments, IPython, Jupyter (aka IPython Notebook) or bpython
should be used. They are more capable than the basic interpreter, and
even have more features than IDLE.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] idle??

2016-01-14 Thread Chris Warrick
On 13 January 2016 at 21:49, Mark Lawrence  wrote:
> On 09/01/2016 10:38, Chris Warrick wrote:
>>
>> On 8 January 2016 at 20:07, bruce  wrote:
>>>
>>> So, where does IDLE fit into this
>>
>>
>> IDLE is a sad little “IDE”, which is really ugly, because it’s written
>> in Tk. It lacks many IDE features. It comes with a really basic
>> debugger (that doesn’t even highlight the line that is being currently
>> executed…), function signature hinting, and some code completion.
>>
>
> Please ignore this drivel, he's spouted this before without giving any
> justification.  IDLE is perfectly adequate as a starter for Python.

I’m sorry, which part of “ugly” (which you cannot deny, it doesn’t
match the OS most of the time), “no debugger line highlighting”, “no
line numbering” (which is a crucial feature of any code editor!) is
not enough “justification”?

For learning, a text editor (that’s better than notepad.exe) is
enough. However, the OP explicitly asked for an IDE, and as such, they
should get a good one.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What is the square brackets about?

2016-01-16 Thread Chris Warrick
On 16 January 2016 at 16:51, Ege Berkay Gülcan  wrote:
> def get_(loc, thing):
> if loc==[]: return thing
> return get_(loc[1:], thing[loc[0]])
>
> Hi I am new to Python and I would like to learn about these uses of square
> brackets. I know that loc[1:] means loc list without the first element but
> I do not know the meanings of loc==[] and thing[loc[0]].

loc == [] checks “if `loc` is equal to an empty list”. Note that this
is not a good way to do this. A much better way to spell this would
be:

if not loc:
return thing

thing[loc[0]] means “check what the 0th element of `loc` (`loc[0]`)
is, and use it as an index for `thing` (`thing[…]`).

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] AWS /Django/Apache/Python/Github

2016-02-13 Thread Chris Warrick
On 13 February 2016 at 01:02, sina sareth via Tutor  wrote:
> Hi ThereHow are you looking for good videos on the deploy apps with Python 
> Framework. I wonder if somebody has any good videos. Thanks
> Sina

I don’t have any videos, but I do have a comprehensive tutorial on
deploying a Python application on a Linux server:

https://chriswarrick.com/blog/2016/02/10/deploying-python-web-apps-with-nginx-and-uwsgi-emperor/

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to run a python script

2016-02-20 Thread Chris Warrick
On 20 February 2016 at 17:25, Erol Gericke  wrote:
> I want learn Python programming. Many years ago I taught myself BASIC so I
> have some programming experience.
>
> I have  installed Python 2.7.11 and Notepad ++ on my Win 7 computer. I have
> also edited the PATH variable to include C:\Python27.
>
> However I am unable to run any scripts.
>
> When I type (into the COMMAND PROMPT window) python test.py or
> python C:\python27\test.py  I get SyntaxError: invalid syntax
>
> Until I solve this problem learning programming makes no sense.
>
> Can you please help me, I would appreciate your help.
>
> Thank you in advance,
> Erol Gericke.
> Somerse West. South Africa.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

Please paste the full error message, and your complete source code.
Also, make sure you are running the commands in the regular command
prompt window, and not in a Python-specific one.

Also, your scripts should not live in C:\Python27, because they might
conflict with other things.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to run a python script

2016-02-21 Thread Chris Warrick
Forwarding to mailing list, please use Reply All in the future.

On 21 February 2016 at 09:48, Erol Gericke  wrote:
> Hi Chris,
>
> Thanks for your prompt reply, the problem has been solved!
> I was using the 'python' terminal not the 'DOS' terminal.
>
>  I have created a new directory to hold the *.py scripts.
>
> As I type with only two fingers I want to keep everything as short as
> possible.
> Is there a way to avoid the full path when running a script.
>
> Thanks again, you have revived my interest in Python.
>
> Regards,
> Erol Gericke
>
>
>> Please paste the full error message, and your complete source code.
>> Also, make sure you are running the commands in the regular command
>> prompt window, and not in a Python-specific one.
>>
>> Also, your scripts should not live in C:\Python27, because they might
>> conflict with other things.
>>
>

You can open command prompt in the directory of your scripts [0] or
put them in a directory that doesn’t require a lot of typing (C:\py
for example).

PS. it’s not the “DOS” terminal, it’s the command prompt (cmd.exe).
DOS is not part of Windows NT/2000/XP and better, and rightfully so.

[0]: In Windows 8?/10, available from the File menu. Otherwise:
http://www.askvg.com/enable-open-command-window-here-option-in-context-menu-in-windows-vista/

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Remove artca...@google.com from mailing list, PLEASE

2014-11-04 Thread Chris Warrick
Do it yourself at https://mail.python.org/mailman/listinfo/tutor .

Besides, your email is @gmail.com, not @google.com.
-- 
Chris Warrick <http://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] syntax error with raw input

2014-11-12 Thread Chris Warrick
On Wed, Nov 12, 2014 at 12:08 PM, Vaibhav Banait
 wrote:
> Hi
> I am new to python. I learnt (!) using  raw_input a day back. Attempt to use
> has resulted in error. I am not able to spot a problem in syntax. I am using
> python 3.4.2. Kindly help
>
>
> a = raw_input("Write down your name: ")
>
> Output:
>
>
> Traceback (most recent call last):
>   File "", line 1, in 
> a = raw_input("Write down your name: ")
> NameError: name 'raw_input' is not defined
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

In Python 3, raw_input() was renamed to input().

a = input("Write down your name: ")

Note that input() is also a thing in Python 2, but you shouldn’t use
that one for security reasons.  Python 3’s is fine though.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Decode and Encode

2015-01-28 Thread Chris Warrick
On Wed, Jan 28, 2015 at 10:35 AM, Sunil Tech  wrote:
> Hi All,
>
> When i copied a text from web and pasted in the python-terminal, it
> automatically coverted into unicode(i suppose)
>
> can anyone tell me how it does?
> Eg:
>>>> p = "你好"
>>>> p
> '\xe4\xbd\xa0\xe5\xa5\xbd'
>>>> o = 'ªîV'
>>>> o
> '\xc2\xaa\xc3\xaeV'
>>>>

No, it didn’t.  You created a bytestring, that contains some bytes.
Python does NOT think of `p` as a unicode string of 2 characters, it’s
a bytestring of 6 bytes.  You cannot use that byte string to reliably
get only the first character, for example — `p[0]` will get you
garbage ('\xe4' which will render as a question mark on an UTF-8
terminal).

In order to get a real unicode string, you must do one of the following:

(a) prepend it with u''.  This works only if your locale is set
correctly and Python knows you use UTF-8.   For example:

>>> p = u"你好"
>>> p
u'\u4f60\u597d'

(b) Use decode on the bytestring, which is safer and does not depend
on a properly configured system.

>>> p = "你好".decode('utf-8')
>>> p
u'\u4f60\u597d'

However, this does not apply in Python 3.  Python 3 defaults to
Unicode strings, so you can do:

>>> p = "你好"

and have proper Unicode handling, assuming your system locale is set
correctly.  If it isn’t,

>>> p = b"你好".decode('utf-8')

would do it.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can a virtual environment be renamed?

2017-04-16 Thread Chris Warrick
On 16 April 2017 at 16:45, Jim  wrote:
> My system python is 2.7.12 so I created a virtual environment using venu to
> run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 and
> put it in env36. Is it possible to change env to env35 for 3.5.2 without
> breaking things?

No. You need to delete your existing virtualenv and create a new one.
You can just use `pip freeze > requirements.txt` in the old one and
run `pip install -r requirements.txt` in the new one to ”move” all the
packages you had.


-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can a virtual environment be renamed?

2017-04-16 Thread Chris Warrick
On 16 April 2017 at 18:16, Jim  wrote:
> On 04/16/2017 10:10 AM, Chris Warrick wrote:
>>
>> On 16 April 2017 at 16:45, Jim  wrote:
>>>
>>> My system python is 2.7.12 so I created a virtual environment using venu
>>> to
>>> run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 and
>>> put it in env36. Is it possible to change env to env35 for 3.5.2 without
>>> breaking things?
>>
>>
>> No. You need to delete your existing virtualenv and create a new one.
>> You can just use `pip freeze > requirements.txt` in the old one and
>> run `pip install -r requirements.txt` in the new one to ”move” all the
>> packages you had.
>>
>>
>
> Thanks Chris. I thought that would be the answer but wanted to check before
> I spent a lot of time trying to do something that was not possible.
>
> Virtual environments tend to confuse me. My system is Mint 18.1 with 2.7.12
> & 3.5.2 installed. So I would have to download a tar file of 3.6, then build
> it and then use it's version of venv to create a virtual environment to try
> 3.6. Is that correct?

Yes, you need to install the appropriate interpreter first, and
likewise a virtualenv won’t work if you uninstall an
interpreter/upgrade it to a new minor version*. You might not need to
use the source tarball if
https://launchpad.net/~fkrull/+archive/ubuntu/deadsnakes works on Mint
(and if you do use tarballs, make sure to install somewhere in /opt or
whatever not to make a mess — it’s easy to break your OS if you’re not
careful)

* eg. 3.5 → 3.6. Won’t ever happen on Mint or other “friendly”
distros, unless you do a dist-upgrade. Happens pretty often on
rolling-release distros or macOS with homebrew.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Recommended Python Compiler

2017-07-31 Thread Chris Warrick
On 31 July 2017 at 14:45, Wolfgang Maier
 wrote:
> On 07/31/2017 03:31 AM, Mats Wichmann wrote:
>>
>> since this all opinions :), I don't think idle is worth bothering with.
>> for editor that can do ide like things, consider atom (free, get a bunch of
>> plugins) or sublime text (not free). for a full ide, pycharm is great
>> (community edition free). for a lightweight ide to get started, i liked
>> thonny when i trialed it at somebody's request, but do look at that wiki
>> page, tons of choices there.
>
>
> As you're saying, it is all about opinion here so let me defend IDLE here.
> There may be more powerful IDEs than IDLE, but it takes you a long way (far
> beyond beginner/scripting level) and, of interest if you are ever writing
> Python code on a Windows machine, typically comes installed together with
> the Python interpreter there, so you will find it on many machines (even
> ones you are not allowed to install other software on).

IDLE is one step up from Notepad. Which makes it a pretty terrible
editor. It even lacks line numbers, which is an elementary feature,
and a necessity for debugging (tracebacks!)

On the other hand, some of the better editors (eg. Visual Studio Code)
provide .zip packages that do not require installation and can even
run off a USB stick.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if __name__=='main' vs entry points: What to teach new comers?

2017-08-01 Thread Chris Warrick
On 1 August 2017 at 16:54, Thomas Güttler  wrote:
> I have a friend who is a talented shell script writer. He is a linux guru
> since
> several years.
>
> He asked me if "if __name__=='main':" is state of the art if you want
> to translate a shell script to python.
>
> I started to stutter and did not know how to reply.
>
> I use Python since several years and I use console_script in entry_points of
> setup.py.
>
> I am very unsure if this is the right way if you want to teach a new comers
> the joy of python.
>
> In the current context we want to translate a bunch of shell scripts to
> python scripts.
>
> What do you think?
>
> Regards,
>   Thomas Güttler
>
>
> --
> Thomas Guettler http://www.thomas-guettler.de/
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

Do both. If you’re making a package, create a __main__.py file as well
so your package is usable with `python -m somepackage`. On the other
hand, if you’re making things more akin to shell scripts, using just
entry_points makes stuff harder, because you need to install the code
(and write a setup.py), as opposed to just putting the script
somewhere in $PATH.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setup.py "script" vs "console_scripts" Was: if __name__=='main' vs entry points: What to teach new comers?

2017-08-03 Thread Chris Warrick
On 3 August 2017 at 09:52, Thomas Güttler  wrote:
>
>
> Am 02.08.2017 um 18:06 schrieb Wolfgang Maier:
>>
>> On 08/02/2017 04:57 PM, Steven D'Aprano wrote:
>>>
>>> On Wed, Aug 02, 2017 at 10:48:39PM +1000, Ben Finney wrote:
>>>>
>>>> Thomas Güttler  writes:
>>>>
>>>>> Maybe I am doing something wrong.  I was proud because I did use
>>>>> “console_scripts” entry points.
>>>>
>>>>
>>>> Did someone lead you to believe it was wrong? Setuptools console_scripts
>>>> entry points are a good tool.
>>>>
>>>> My point was that it is an *advanced* tool, difficult to use and also
>>>> difficult to explain because the concepts are advanced.
>>>
>>>
>>> Can you explain the use-case for when somebody might want to use
>>> console_scripts entry points?
>>>
>>> I have a module with a main() function and an "if __name__ == ..."
>>> guard. Under what circumstances is that not sufficient, and I would want
>>> console_scripts?
>>>
>>
>> If you install things using pip/setuptools and have defined a
>> console_scripts entry point for it, then the corresponding wrapper
>> script will be installed in whatever is considered the scripts directory
>> at install time on that machine. With a bit of luck the entry point will
>> thus be executable directly without any end-user intervention (like
>> adding folders to $PATH and chmodding files).
>> Personally, I always found it straightforward to write the wrapper
>> script myself, then define this as a 'scripts' file in the package
>> layout of my setup.py, but people's MMV.
>
>
>
> I was not aware of "scripts" in setup.py. But I found docs:
>
>   http://python-packaging.readthedocs.io/en/latest/command-line-scripts.html
>
> Why are there two ways: "script" vs "console_scripts entry-point"?

Simple: `scripts` are legacy. `entry_points` are the new thing.
There’s also a third approach: gui_scripts entry_points, which work
the same way on Linux/*nix, but on Windows, it means that running your
script by opening the created .exe files does not show a console
window. Note that stdout/stderr do not work in that mode under
Windows, which can lead to spurious application crashes.  (GUI-only
processes cannot use stdout/stderr because they don’t have a console
attached)

I’ll take the liberty to link my (better) blog post about this:
https://chriswarrick.com/blog/2014/09/15/python-apps-the-right-way-entry_points-and-scripts/

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setup.py "script" vs "console_scripts" Was: if __name__=='main' vs entry points: What to teach new comers?

2017-08-04 Thread Chris Warrick
On 4 August 2017 at 12:15, Thomas Güttler  wrote:
> Chris wrote "Simple: `scripts` are legacy."
>
> You say it is the standard, and console_scripts is from a third party.
>
> For me "legacy" sound like "don't go this old way".
>
> For me "third party" sounds like "don't go this way, stick to the standard".
>
> I feel stupid since I have no clue.

The official docs recommend distutils:

https://docs.python.org/2/library/distutils.html

> Most Python users will not want to use this module directly, but instead use 
> the cross-version tools maintained by the Python Packaging Authority. In 
> particular, setuptools is an enhanced alternative to distutils that provides:
> [snip]
> * the ability to declare project “entry points”, which can be used as the 
> basis for application plugin systems
> * the ability to automatically generate Windows command line executables at 
> installation time rather than needing to prebuild them

And, as eryk sun mentioned, recent Python 2.7 and 3.4 versions ship
setuptools and pip, via the ensurepip module.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setup.py "script" vs "console_scripts" Was: if __name__=='main' vs entry points: What to teach new comers?

2017-08-08 Thread Chris Warrick
On 8 August 2017 at 03:30, Ben Finney  wrote:
> Thomas Güttler  writes:
>
>> Why is "the sane default is 'use console_scripts entry-point in
>> setup.py'" not a good answer?
>
> Because third-party Setuptools is required for entry points, which means
> entry points cannot be a default choice.
>
> It may well be a good choice for many cases. But that's a different
> matter from it being a good *default* choice; it can only be a default
> choice if it's in the standard library.

While setuptools is not officially part of the stdlib, it *is*
recommended by the official documentation, the dev team, and it’s
available pretty much everywhere. setuptools can’t be in stdlib,
because it’s moving too fast for stdlib to keep up.

Look here: http://pythonwheels.com/ — 254 of the top 360 packages on
PyPI use wheels. It means that at least that many use setuptools;
sometimes with a distutils fallback, but often without one. Moreover,
many of the packages without wheels use setuptools as well.

The sane default choice is entry_points.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setup.py "script" vs "console_scripts" Was: if __name__=='main' vs entry points: What to teach new comers?

2017-08-10 Thread Chris Warrick
On 9 August 2017 at 23:15, Steven D'Aprano  wrote:
> On Tue, Aug 08, 2017 at 12:56:56PM +0200, Chris Warrick wrote:
>
>> While setuptools is not officially part of the stdlib,
>
> This is the critical factor. How can you use *by default* something that
> is *NOT* supplied by default?
>
> Obviously you cannot. It is physically impossible.


The problem with setuptools (and pip) is that they are not first-party
stdlib members, but they are not third-party packages either. They’re
somewhere in between. They have been blessed by the core developers.
And yes, setuptools might be in all the places you mentioned:

> But this does NOT hold for everyone, possibly not even for the majority
> of Python users. For example:
>
> - students using their school's computers;
>
> - corporate and government users using a SOE (Standard Operating
>   Environment);
>
> - people using a system where, for policy reasons, only the
>   standard library is permitted.

* If those computers run Windows (as they often do) and run a recent
Python version (3.4 or newer/2.7.9 or newer), setuptools will be
installed, unless the IT people explicitly disabled ensurepip.
* On macOS, setuptools will be installed if they’re using the system
Python, the python.org installers (which are not uninstallable), or
Python from Homebrew. The last two also have pip, and system Python
has ensurepip.
* On Linux, setuptools/pip is likely to be there, but it’s not
required in all distributions. (Fedora mandates setuptools; Debian
even rips out ensurepip by default and hides it in python3-venv
because reasons…)

If the users are meant to install Python packages, their system
administrators would take care of that — either by setting up
setuptools/pip and perhaps virtualenv, or taking install requests from
users. If users are not supposed to be running setuptools/pip, they
probably shouldn’t, but they can still install it from ensurepip or
downloading get-pip.py.

> I've worked in places where installing unauthorized software was a
> firing offence.

Those people don’t need setuptools. Those people should not be using
distutils either. They might not even be allowed to download packages
and run __main__.py without installation.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Percentage of installations without setuptools (Was if __name__=='__main__' ...)

2017-08-11 Thread Chris Warrick
On 11 August 2017 at 19:54, Mats Wichmann  wrote:
> On 08/11/2017 09:54 AM, Alan Gauld via Tutor wrote:
>> On 11/08/17 13:35, Thomas Güttler wrote:
>>
>>> I guess most python installations have setuptools.
>>
>> I guess so too, although I don't know.
>> Those that don't are probably in one of two categories
>> a) people who just downloaded Python and never installed
>>anything else

False since Python 3.4/2.7.9. ensurepip installs Python on every new
Python install.

> Most Linux distributions choose to make it a separate package.  I have
> it (them - one for Py2 and one for Py3) installed everywhere, but I'd
> guess it's not a default install then.
>
> Fedora:
> python2-setuptools-36.2.0-1.fc26.noarch
> python3-setuptools-36.2.0-1.fc26.noarch
>
> Ubuntu:
> Desired=Unknown/Install/Remove/Purge/Hold
> |
> Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
> |/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
> ||/ Name  Version  Architecture Description
> +++-=---=
> ii  python-setuptools 33.1.1-1 all  Python Distutils
> Enhancements
> ii  python3-setuptools33.1.1-1 all  Python3 Distutils
> Enhancements

On Fedora, setuptools is mandatory:

package: python3-3.6.2-1.fc26.x86_64
[snip some unrelated stuff]
  dependency: python3-pip
   provider: python3-pip-9.0.1-9.fc26.noarch
  dependency: python3-setuptools
   provider: python3-setuptools-36.2.0-1.fc26.noarch

On other distributions, it usually isn’t, although many users will
eventually end up with a copy.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] intro book for python

2017-09-01 Thread Chris Warrick
I would recommend reading the official Python tutorial [0] This
tutorial will explain the important parts of Python. It doesn’t spend
too much time explaining programming basics though.

My alternate recommendations include Think Python [1] or Automate the
Boring Stuff with Python [2].


On 1 September 2017 at 19:51, Raghunadh  wrote:
> Hello Derek,
>
> I would start with this book
>
> hxxps://learnpythonthehardway.org
>
> Raghunadh

LPTHW is a terrible book: slow and boring, tells readers to memorize
truth tables instead of understanding them (sic!), 19% of it is
thoughtlessly teaching print() — overall, a failure at teaching people
to program. Moreover, the author wrote a nonsensical essay bashing
Python 3 [3] (debunked in [4]), and released a Python 3.6 version of
his book shortly afterwards.

[0] https://docs.python.org/3/tutorial/index.html
[1] http://greenteapress.com/wp/think-python-2e/
[2] https://automatetheboringstuff.com/
[3] https://learnpythonthehardway.org/book/nopython3.html
[4] https://eev.ee/blog/2016/11/23/a-rebuttal-for-python-3/

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3 for Beginners was: (Re: intro book for python)

2017-09-03 Thread Chris Warrick
On 3 September 2017 at 12:02, Leam Hall  wrote:
mmend anything from the author of LPTHW after he had the
>> audacity to write this https://learnpythonthehardway.org/book/nopython3.html
>> about Python 3, in addition to which there are several vastly superior books
>> and/or tutorials anyway.
>>
>> Kindest regards.
>>
>> Mark Lawrence.
>
>
> There are lots of other books on Python, that's true. "Practical
> Programming" (Gries, Campbell, Montojo) is one I use.
>
> Are you going to toss "Learning Python" since Mark points out some of
> python's drift from it's core values?
>
> I appreciate that link. Zed's right.

Many of Zed’s argument are false and plain BS:
https://eev.ee/blog/2016/11/23/a-rebuttal-for-python-3/

> Python 3 isn't used by the OS tools on Red Hat, and that's that major Linux 
> vendor in the US.

This will change in RHEL 8, whenever that comes out: yum was replaced
by dnf a few versions of Fedora ago, and that’s written in Python 3.

> Anyone that uses python on Linux has to use Python 2. That means Python 3 is
> just one more language that requires work to install and maintain. I'm not
> seeing the benefits. How long has Python 3 been out? How many others are
> seeing the benefits of total change? When will people who say "you should
> upgrade" realize it's weeks or months of work with no real reason to do so?

You’re getting: sane Unicode support, f"strings", type hinting,
pathlib, asyncio, and a few more improvements.

> Yesterday I was coding and had to work around Python 3 dict.keys() returning
> a "dict_keys" type vs a list. Why did we need another type for this? I'm a
> coding beginner.

Performance and resource usage. If you use a list, Python needs to do
some extra work to convert internal data structures of a dict into a
list, and also store that new list in memory.

> I can talk a decent game in a few languages like python but
> I'm not experienced enough or smart enough to deal with these sorts of
> problems easily. Returning a new type, without significant benefit, makes it
> harder for people to progress in the language.

There are a lot of things that return iterators or other fancy types
instead of lists in Python 3 (eg. zip, range, all of itertools). You
can always iterate over those like you would, and if you need a list
for some reason, you can just call list(the_thing).

> Some years ago I wanted to play with an IRC bot sort of thing. Someone on
> Freenode #python mentioned Twisted so I got that and started playing. Half
> an hour, maybe forty five minutes later and my little project did what I was
> trying to do. This was before I really knew any python; the language was
> that clean and easy to learn.

You can still do that with Python 3. (Although you’ll be better off
using asyncio and some IRC lib for that.)

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2017-09-06 Thread Chris Warrick
On 6 September 2017 at 08:39, edmundo pierre via Tutor  wrote:
> Hi Python,
> I am trying to make a french to English dictionary. First of all, I made a 
> dictionary with keys and values. Then I asked the user to enter a letter. If 
> the letter correspond to the Keys, my print function should display the Key 
> and value. But my code below, could not . Thank you!
>
> List ={"le":"…"}
(it”s called dict, or dictionary, and “List”/“dict” are not good variable names)

> keys = List.keys()print(keys)
> a = str(input(""))
> if 'a' in keys:print(a + ":"+ List['a'])else:print("impossible")

You’re trying to find the letter 'a' and print it, you aren’t using
the variable a. Don’t put it in quotes. So, do it like this:

data = {"le": "…"}
print(data.keys())
search_key = str(input("> "))
if search_key in data:
print(search_key, ":", data[search_key])
else:
print("Not in dictionary.")

(I also cleaned it up a little)

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How is database creation normally handled?

2017-09-10 Thread Chris Warrick
On 10 September 2017 at 02:29, boB Stepp  wrote:
> While reading about SQL, SQLite and the Python module sqlite3, it
> appears that I could (1) have a program check for the existence of the
> program's database, and if not found, create it, make the tables,
> etc.; or, (2) create the database separately and include it with the
> program.  What are the pros and cons of each approach?  (1) to me
> looks only helpful if I wish to write a program that might want to
> allow the user to have multiple databases.  But this sounds like a lot
> of extra coding and checking to make it work well.  But if I only wish
> to have a single database, then (2) sounds like the approach to use.
> I would create the database, populate it with the needed empty tables
> with the desired fields, making it ready to use by the program's user.
>
> Not having any experience in the database arena, I'm not even sure I
> know how to properly think about this.

A separate database creation script will be better. It’s good to
separate the logic of your app and configuration/setup — just like you
shouldn’t be “helpfully” installing dependencies when someone runs
your script.

For a good approach, look at Django: every app (sub-package of a site)
has its own set of migrations. Migrations are responsible for creating
tables, and more importantly — for updating them. Because you will
need to make changes to your original DB structure throughout the
lifetime of your software. I built a small Django app over the
weekend, and I’ve created 10 migrations throughout the process¹, and
that will probably be true of your project. Now, if those migrations
would have to go to the main codebase instead of a side directory, it
would be a burden to maintain. If there were no migration frameworks,
I’d have to include something like “run this SQL to upgrade your DB
when upgrading from version 0.1.0 to 0.1.1”, which is even less fun.

So, when I make some change to my models.py (which has the database
schema), I can just run:
./manage.py makemigrations
./manage.py migrate
and my database will be magically updated, hassle-free and I don’t
even have to look at the auto-generated code.

(If you are writing a web app: do look at Django! If you aren’t:
Alembic does the same thing for SQLAlchemy. Something for plain
sqlite3 may or may not exist.)

¹ Progressive enhancement: adding more features that need extra
columns I didn’t think of first. Or removing features that weren’t
cool. Or restoring them the next day.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess.getstatusoutput : UnicodeDecodeError

2017-09-22 Thread Chris Warrick
On 22 September 2017 at 03:57, Evuraan  wrote:
>>>> result = subprocess.run(["tail", "-400", "/tmp/pmaster.txt"], 
>>>> stdout=subprocess.PIPE)
>>>> result.returncode
> 0
>>>> subprocess.getstatusoutput("file  /tmp/pmaster.txt",)
> (0, '/tmp/pmaster.txt: Non-ISO extended-ASCII text, with very long
> lines, with LF, NEL line terminators')
>>>>

You’re still using the deprecated function.

>>> subprocess.run(['file', '/tmp/pmaster.txt'], stdout=subprocess.PIPE)
CompletedProcess(args=['file', '/tmp/pmaster.txt'], returncode=0,
stdout=b'/tmp/pmaster.txt: Non-ISO…\n')
>>> result = _  # underscore means result of previous line in interactive mode
>>> result.stdout
b'/tmp/pmaster.txt: Non-ISO…line terminators\n'
>>> result.returncode
0

And if you want to get a Unicode string (if output of command is your
system encoding, hopefully UTF-8):

>>> subprocess.run(['file', '/tmp/pmaster.txt'], stdout=subprocess.PIPE, 
>>> universal_newlines=True)
CompletedProcess(args=['file', '/tmp/pmaster.txt'], returncode=0,
stdout='/tmp/pmaster.txt: Non-ISO…\n')
>>> (_.stdout is an unicode string)

Also, going back to your original example: you should not be using
`tail` from within Python. You should not depend on tail being
available (it’s not on Windows), and there may also be version
differences. Instead of tail, you should use Python’s standard file
operations (open()) to accomplish your task.

[advertisement] Extra reading on security (shell=False) and the
necessity of calling subprocesses:
https://chriswarrick.com/blog/2017/09/02/spawning-subprocesses-smartly-and-securely/
[/advertisement]

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A Question Regarding the Documentation Format

2017-09-24 Thread Chris Warrick
On 23 September 2017 at 15:15, Prateek  wrote:
> input(...)
> input([prompt]) -> string
>
> I want to know what the significance of  "-> string". I have tried
> consulting several books but none of them gave me a clear-cut explanation
> for this.

This indicates the return type: input() returns a string.

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to write a function which reads files

2018-08-07 Thread Chris Warrick
On Tue, 7 Aug 2018 at 15:07, Rafael Knuth  wrote:
> def FileReader(file_path):
> with open(file_path) as file_object:
> contents = file_object.read
> return contents
>
> print(FilePrinter("C:\\Users\\...\\MyFile.txt")) # path shortened for
> better readability
>
> I got this error message:
>
> 

You forgot the parentheses (), and are returning a reference to the
function instead of calling it and returning its result. Do this:
contents = file_object.read()

Also, consider using snake_case instead of PascalCase for your
function name, since the latter is typically used for classes, and
perhaps call it read_file to better describe it?

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor