[Tutor] Clear screen questions

boB Stepp robertvstepp at gmail.com
Mon May 6 04:10:01 CEST 2013


On Sun, May 5, 2013 at 7:54 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 06/05/13 10:17, boB Stepp wrote:
>>
[...]
>
> But even on Windows that will not work, if you are running under IDLE. And
> unfortunately there is no official way to tell if you are running under
> IDLE, or any other IDE for that matter.
>

I was not expecting it to work under any IDE. With IDLE I was just
curious if it would generate some sort of error or other unexpected
behavior. But you make a good point: If possible my code should run
properly even under an IDE if it is possible to cover that scenario.

>
>> So my main question is there a truly clean, cross-platform solution to
>> the clear screen dilemma? If my online searching is accurate, then the
>> answer appears to be no, unless one wants to print many blank lines.
>
>
> Your googling is accurate. There is no clean, cross-platform solution, not
> even for the "main three" (Linux/Unix, Windows, Mac), let alone minority and
> legacy platforms, other implementations, etc.
>

So it appears that the only way to cover the various possibilities is
to query for the platform being used and then apply the correct
statement for that platform. And it still would not work for the point
noted above. Could be a lot of effort for little gain!

>
>> A second question is that one person had as the answer to use:
>>
>> os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )
>>
>> I don't understand this syntax. The writer said that if one
>> understands what this is doing, then the method is more generally
>> useful. Would someone explain how this works? And hopefully it will
>> become apparent to me how this is more generally useful?
>
>
>
> You start with a call to os.system. What's the argument to os.system? Well,
> *eventually* is has to become a single string, but it can be an expression
> that evaluates to a string. What is this expression? It starts with a list
> of two strings:
>
> ['clear', 'cls']
>
>
> which is then indexed by the result of another expression, os.name == 'nt'.
> Under Windows, this evaluates to True, otherwise to False:
>
> ['clear', 'cls'][True]  # under Windows
> ['clear', 'cls'][False]  # everything else
>
>
> A little known fact: True evaluates as equal to 1, and False as equal to 0.
> (This is mostly for historical reasons, but it's also useful.) So the above
> ends up as:
>
> ['clear', 'cls'][True]  # under Windows
> => 'cls'
>
> ['clear', 'cls'][False]  # everything else
> => 'clear'
>
>
> and finally os.system gets to run a single string.
>
Thanks for the very clear explanation! I was not thinking in list
terms when I saw the first pair of brackets, so it did not occur to me
to see the second set of brackets as indexing.

boB


More information about the Tutor mailing list