Re: [Tutor] finding difference in time

2009-05-15 Thread Martin Walsh
Kent Johnson wrote:
> On Fri, May 15, 2009 at 12:46 AM, R K  wrote:
>> Gurus,
>>
>> I'm trying to write a fairly simple script that finds the number of hours /
>> minutes / seconds between now and the next Friday at 1:30AM.
>>
>> I have a few little chunks of code but I can't seem to get everything to
>> piece together nicely.
>>
>> import datetime,time
>> now = datetime.datetime.now()
>>
>> i = 0
>> dayOfWeek = datetime.datetime.now().strftime( '%a' )
>> while dayOfWeek != 'Fri':
>> delta = datetime.timedelta( days = i )
>> tom = ( now + delta ).strftime( '%a' )
>> if tom != 'Fri':
>> i = i + 1
>> else:
>> print i
>> print tom
>> break
>>
>> So with this code I can determine the number of days until the next Friday
>> (if it's not Friday already).
> 
> This could be simpler. I would write
> nextFriday = datetime.datetime(now.year, now.month, now.day, 1, 30, 0)
>  while nextFriday.weekday() != 4:
>   nextFriday += datetime.timedelta(days=1)
> 
> Note the use of datetime attributes instead of relying on strftime().
> 
> What do you want the answer to be if you run the script at 1am Friday?
> at 2am Friday? If you want the next Friday in both cases, you could
> write this as
> nextFriday = datetime.datetime(now.year, now.month, now.day, 1, 30, 0)
> nextFriday += datetime.timedelta(days=1) # Make sure to get a Friday
> in the future
>  while nextFriday.weekday() != 4:
>   nextFriday += datetime.timedelta(days=1)

I don't believe you'll get much better than that, IMHO.

But, dateutil (3rd party) probably deserves a mention, at least, for
this kind of job. I'm pretty sure the dateutil equivalent of Kent's
second approach would look something like this, but I haven't thoroughly
tested it, YMMV ...

from datetime import datetime
from dateutil.relativedelta import relativedelta, FR

now = datetime.now()
delta = relativedelta(
days=1, weekday=FR, hour=1,
minute=30, second=0, microsecond=0
)
nextFriday = now + delta

print nextFriday

...

dateutil totally rocks, and I hope someday soon it will be included in
the standard library.

http://labix.org/python-dateutil

HTH,
Marty





___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python popen command using cat > textfile .... how to terminate

2009-05-15 Thread Noufal Ibrahim

MK wrote:

Hi there,

i am using this code to send an "cat > ThisIsMyUrl" with popen.
Of cos cat now waits for the CTRL+D command. 
How can i send this command ?


Wouldn't it be better if you directly opened the "ThisIsMyUrl" file and 
wrote the text into it rather than rely on shelling out for this?


[..]

--
~noufal
http://nibrahim.net.in/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python popen command using cat > textfile .... how toterminate

2009-05-15 Thread Steve Willoughby
On Fri, May 15, 2009 at 08:51:26AM -0700, Steve Willoughby wrote:
> On Fri, May 15, 2009 at 04:18:16PM +0100, Alan Gauld wrote:
> > echo ^D | cat > foo
> > 
> > sends a CtrlD to cat which writes an empty file to foo.
> 
> And since this seems to be a point of confusion for you,

And that was actually supposed to be addressed to the original
poster, who seemed to be confused about where the ^D character
was going, not Alan.

-- 
Steve Willoughby|  Using billion-dollar satellites
st...@alchemy.com   |  to hunt for Tupperware.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python popen command using cat > textfile .... how toterminate

2009-05-15 Thread Steve Willoughby
On Fri, May 15, 2009 at 04:18:16PM +0100, Alan Gauld wrote:
> echo ^D | cat > foo
> 
> sends a CtrlD to cat which writes an empty file to foo.

And since this seems to be a point of confusion for you,
keep in mind that the ^D character itself is not a "command"
or even seen by the cat program at all.  So the notion of
"sending ^D to cat" via the interprocess pipe from Python
isn't really the right concept.  You never send ^D to cat.

When cat (or any program) is expecting input (say, from its
standard input device) which is coming from your terminal
(i.e., reading in whatever you're typing), then ^D is the
default character the *Unix I/O system* recognizes as 
signalling the end of input for that device.  This will cause
*the OS* to close that input device.  All the cat program sees
is that its input has run out of data.

The same is true on other OSes like VMS or DOS or Windows,
which use ^Z to mean the same thing (and note that even
on Unix you can assign a different key than ^D if you want
to).

That's why from Python, when you're not using the normal
TTY control support from the OS itself, but sending data
to cat from your Python program, there's no notion of ^D,
but you do the same thing to cat that the OS would do:
you close the input device.

I hope that makes it clearer.

> And all of them are a bad way to create an empty file in either *nix or 
> Python.

Very much so.  But don't feel bad, this is a very common 
mistake for beginners to make.  Cat has a number of uses it's
well suited for, but don't fall into the trap of using it for
everything when there are better tools available.  I seem to
keep running into people who do things like

  $ cat myfile | more

because they just learned the pattern "cat file |..." without
really learning how to use file redirection and how these things
work.

But more importantly, don't fall into the trap of launching
external programs to do simple tasks which are already built
into your language.  You just introduce extra code you don't
need, dependencies on the OS platform you don't need, and 
security and performance problems as an extra bonus.

> When working in Python, every time you are tempted to call
> a unix command via os.system/popen etc check to see if
> there is a way to do it from within python fiorst.
> There often is.

Almost always.  Plus, if you do it in Python your program
will work on Windows.  And MacOS.  And VMS.  And a Unix
system where the user has a "cat" program which behaves
differently than yours does... which trying to call 
"cat" yourself won't.

 
> HTH,

HAND,

-- 
Steve Willoughby|  Using billion-dollar satellites
st...@alchemy.com   |  to hunt for Tupperware.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python popen command using cat > textfile .... how toterminate

2009-05-15 Thread Alan Gauld


"MK"  wrote


Seems that i did it the wrong way still from the beginning.
I did it now with open and write an empty file.

But anyway i would wish to know if it is possible to terminate
a running cat.


It depends on what you mean by a running  cat.

cat simply concatenates (ie joins) its input to its output.
By default cat's input is stdin and its output is stdout
so if you just type cat anything you type on stdin gets
echoed to stdout. You terminate the command by
inputing an EOF character (Ctrl D on *nux)

cat > foo

writes stdin to foo
Again, to terminate it you send EOF via stdin.
So if you use subprocess/popen to run cat you need
to write EOF to the stdin port. You can do that with
popen2 or subprocess.Popen but not with simple
popen which only lets you read stdout.

cat > foo < /dev/null

writes the non file at dev/null to foo and since that
has an implicit EOF it terminates automatically

echo ^D | cat > foo

sends a CtrlD to cat which writes an empty file to foo.

Your questions are simply about how to run cat not
about Python. Any/All of the above can be run from
Python.

And all of them are a bad way to create an empty file in either *nix or 
Python.


In *nix use touch and in Python use

open(foo,'w').close()

When working in Python, every time you are tempted to call
a unix command via os.system/popen etc check to see if
there is a way to do it from within python fiorst.
There often is.


HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python popen command using cat > textfile .... how to terminate

2009-05-15 Thread Lie Ryan

MK wrote:

Ok. I explain it once more. Its not about reading the console output of
the command. Its that i want to put a empty file in my subdirectories
so that the name of the file is a message or url or something else.
And if you want an empty file you can do that with 
"cat > IAmAnEmptyFileWithOnlyAName"

under linux on the CLI.


But why not using open('filename', 'w')?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] finding difference in time

2009-05-15 Thread Dave Angel

R K  wrote:


Gurus,

I'm trying to write a fairly simple script that finds the number of hours / 
minutes / seconds between now and the next Friday at 1:30AM.

I have a few little chunks of code but I can't seem to get everything to piece 
together nicely.

import datetime,time
now = datetime.datetime.now()

i = 0
dayOfWeek = datetime.datetime.now().strftime( '%a' )
while dayOfWeek != 'Fri':
delta = datetime.timedelta( days = i )
tom = ( now + delta ).strftime( '%a' )
if tom != 'Fri':
i = i + 1
else:
print i
print tom
break

So with this code I can determine the number of days until the next Friday (if 
it's not Friday already).

The problem I'm having, however, is with finding the number of minutes until 
1:30AM on Friday.

nextFridayDay = int( now.strftime( '%d' ) ) + 1
nextFridayMonth = int( now.strftime( '%m' ) )
nextFridayYear = int( now.strftime( '%Y' ) )

nextRun = datetime.datetime( nextFridayYear , nextFridayMonth , nextFridayDay , 
1 , 30 , 0 )

What I gather is that I should be able to numerically manipulate two datetime 
objects, as seen below:

In [227]: nextRun - now  
Out[227]: datetime.timedelta(0, 46155, 51589)


The result, however, doesn't make sense. Take a look...

In [231]: d = nextRun - now

In [232]: d.seconds
Out[232]: 46155

In [233]: d.days
Out[233]: 0

Thoughts on what I may be doing wrong? Am I going about this the whole wrong 
way? Should I be using something different to calculate the number of minutes 
between now and the next Friday at 1:30AM?
  
Could you give us the exact wording of the homework assignment?  I 
suspect that if now is on a Friday, and already past 1:30, then you 
want  to target a week from today, rather than getting negative numbers.


If so, you can't treat day-of-week as something independent.  If you 
want to keep your present loop, you should first compare now's hour and 
minute to 1:30.


Second problem, you're not using the result of the loop.  You could use 
either delta or i as some indication of how many days are between now 
and Friday.  I suspect you intended for the +1 on nextFridayDay to be +i 
instead.  Unfortunately, that would help any time except during the last 
week of the month (and year).


Fixing each of these in isolation would make the code painfully convoluted.

Seems to me you should be finding your target date as a timedate object, 
and manipulating that object directly till it represents a time of 1:30, 
a day of Friday, and a delta that's positive.


So as an outline:
  make a copy of now, and call it target.
  change target's time fields to be exactly 1:30
  compare target to now, and if smaller, increment it by a delta of 
exactly one day
  in a loop, check if target's day-of-week is 'Fri' and increment by 
another day if not

  Now you have final target, so do your difference.



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python popen command using cat > textfile .... how to terminate

2009-05-15 Thread A.T.Hofkamp

MK wrote:

Ok. I explain it once more. Its not about reading the console output of
the command. Its that i want to put a empty file in my subdirectories
so that the name of the file is a message or url or something else.
And if you want an empty file you can do that with 
"cat > IAmAnEmptyFileWithOnlyAName"

under linux on the CLI.


'touch filename' is easier when you know the file does not yet exist.

Alternatively, you can do 'cat > filename < /dev/null'


But the problem or advantage of is that you can put some lines in
the text file if you want. And if youre ready youm must
terminate the console/terminal with CTRL+D so that cat knows
that the input is finished.


CTL+D means EOF. In a program you express that by closing the file handle.

fp = open('xyz', 'w')
fp.close()

for creating an empty file, thus

fp = subprocess.   #get file handle for writing data to the child
fp.close()

for stating that you have no data for the child process.


I have no lines i want to input in the file. So i must only send
and CTRL+D to cat again that it terminates.

Actually a very simple way i thought. But maybe not.


It is simple indeed :)
It is not Python specific, but defined by the underlying OS. That is why you 
don't find this information in Python documentation.



Albert


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python popen command using cat > textfile .... how to terminate

2009-05-15 Thread Sander Sweers
2009/5/15 MK :
> Ok. I explain it once more. Its not about reading the console output of
> the command. Its that i want to put a empty file in my subdirectories
> so that the name of the file is a message or url or something else.
> And if you want an empty file you can do that with
> "cat > IAmAnEmptyFileWithOnlyAName"
> under linux on the CLI.

Ah yes, cat is not what you will wan to use. You can use the unix
touch command or use python's open().

Example touch and subproces (untested!).

---
import subprocess
command = subprocess.Popen(['touch',
'/your_filepath/filename'],stdout=subprocess.PIPE)
stdout, stderr = command.communicate()
---

Example open().

---
filename = open('/your_filepath/filename', 'w')
filename.close()
---

> But the problem or advantage of is that you can put some lines in
> the text file if you want. And if youre ready youm must
> terminate the console/terminal with CTRL+D so that cat knows
> that the input is finished.

Like I said above, cat is not the right tool for this. When you use
python's open() you could also write data in the file if needed.

> Actually a very simple way i thought. But maybe not.

It is but only with the right tools ;-)

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] finding difference in time

2009-05-15 Thread Kent Johnson
On Fri, May 15, 2009 at 12:46 AM, R K  wrote:
> Gurus,
>
> I'm trying to write a fairly simple script that finds the number of hours /
> minutes / seconds between now and the next Friday at 1:30AM.
>
> I have a few little chunks of code but I can't seem to get everything to
> piece together nicely.
>
> import datetime,time
> now = datetime.datetime.now()
>
> i = 0
> dayOfWeek = datetime.datetime.now().strftime( '%a' )
> while dayOfWeek != 'Fri':
>     delta = datetime.timedelta( days = i )
>     tom = ( now + delta ).strftime( '%a' )
>     if tom != 'Fri':
>     i = i + 1
>     else:
>     print i
>     print tom
>     break
>
> So with this code I can determine the number of days until the next Friday
> (if it's not Friday already).

This could be simpler. I would write
nextFriday = datetime.datetime(now.year, now.month, now.day, 1, 30, 0)
 while nextFriday.weekday() != 4:
  nextFriday += datetime.timedelta(days=1)

Note the use of datetime attributes instead of relying on strftime().

What do you want the answer to be if you run the script at 1am Friday?
at 2am Friday? If you want the next Friday in both cases, you could
write this as
nextFriday = datetime.datetime(now.year, now.month, now.day, 1, 30, 0)
nextFriday += datetime.timedelta(days=1) # Make sure to get a Friday
in the future
 while nextFriday.weekday() != 4:
  nextFriday += datetime.timedelta(days=1)

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python popen command using cat > textfile .... how to terminate

2009-05-15 Thread MK
Seems that i did it the wrong way still from the beginning.
I did it now with open and write an empty file.

But anyway i would wish to know if it is possible to terminate 
a running cat.

Thank you all.



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python popen command using cat > textfile .... how to terminate

2009-05-15 Thread MK
Ok. I explain it once more. Its not about reading the console output of
the command. Its that i want to put a empty file in my subdirectories
so that the name of the file is a message or url or something else.
And if you want an empty file you can do that with 
"cat > IAmAnEmptyFileWithOnlyAName"
under linux on the CLI.

But the problem or advantage of is that you can put some lines in
the text file if you want. And if youre ready youm must
terminate the console/terminal with CTRL+D so that cat knows
that the input is finished.

I have no lines i want to input in the file. So i must only send
and CTRL+D to cat again that it terminates.

Actually a very simple way i thought. But maybe not.

Thank you.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] finding difference in time

2009-05-15 Thread Andre Engels
On Fri, May 15, 2009 at 6:46 AM, R K  wrote:
> Gurus,
>
> I'm trying to write a fairly simple script that finds the number of hours /
> minutes / seconds between now and the next Friday at 1:30AM.
>
> I have a few little chunks of code but I can't seem to get everything to
> piece together nicely.
>
> import datetime,time
> now = datetime.datetime.now()
>
> i = 0
> dayOfWeek = datetime.datetime.now().strftime( '%a' )
> while dayOfWeek != 'Fri':
>     delta = datetime.timedelta( days = i )
>     tom = ( now + delta ).strftime( '%a' )
>     if tom != 'Fri':
>     i = i + 1
>     else:
>     print i
>     print tom
>     break
>
> So with this code I can determine the number of days until the next Friday
> (if it's not Friday already).
>
> The problem I'm having, however, is with finding the number of minutes until
> 1:30AM on Friday.
>
> nextFridayDay = int( now.strftime( '%d' ) ) + 1
> nextFridayMonth = int( now.strftime( '%m' ) )
> nextFridayYear = int( now.strftime( '%Y' ) )
>
> nextRun = datetime.datetime( nextFridayYear , nextFridayMonth ,
> nextFridayDay , 1 , 30 , 0 )
>
> What I gather is that I should be able to numerically manipulate two
> datetime objects, as seen below:
>
> In [227]: nextRun - now
> Out[227]: datetime.timedelta(0, 46155, 51589)
>
> The result, however, doesn't make sense. Take a look...
>
> In [231]: d = nextRun - now
>
> In [232]: d.seconds
> Out[232]: 46155
>
> In [233]: d.days
> Out[233]: 0
>
> Thoughts on what I may be doing wrong? Am I going about this the whole wrong
> way? Should I be using something different to calculate the number of
> minutes between now and the next Friday at 1:30AM?

Why do you think the result doesn't make sense? You basically defined
"next Friday" as tomorrow (the day in the same year on the same day
one number more), and then looked at the time until next Friday at
1:30AM. It appears that that time was 0 days and 46155 seconds (plus
some fraction of a second, which is about 12 hours and 50 minutes.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor