Variable reset

This is the place for queries that don't fit in any of the other categories.

Variable reset

Postby timbo_cole » Sat May 18, 2013 8:24 am

Hi there,

I am new to python but have written some code where I would like a variable to reset back to 0 daily at midnight, is this possibe? How?


Thanks,
Timbo
timbo_cole
 
Posts: 9
Joined: Fri May 17, 2013 8:12 pm

Re: Variable reset

Postby Vik2015 » Sat May 18, 2013 9:31 pm

Hello. You want your script to run when computer is on? If yes just take a look at http://docs.python.org/2/library/time.html, here you can find some helpful stuff! ;)
Vik2015
 
Posts: 21
Joined: Sat May 18, 2013 8:53 pm
Location: Computer

Re: Variable reset

Postby metulburr » Sun May 19, 2013 12:25 am

Vik2015 wrote:You want your script to run when computer is on?

How would you run a script when the computer is off?

You could just run a cronjob to execute a python script to reassign that var to 0 upon midnight
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1476
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Variable reset

Postby timbo_cole » Mon May 20, 2013 7:54 pm

metulburr wrote:
Vik2015 wrote:You want your script to run when computer is on?

How would you run a script when the computer is off?

You could just run a cronjob to execute a python script to reassign that var to 0 upon midnight


how would you link the two python scripts?
timbo_cole
 
Posts: 9
Joined: Fri May 17, 2013 8:12 pm

Re: Variable reset

Postby micseydel » Mon May 20, 2013 8:47 pm

I'm not sure what metulburr meant about that, but I think that threading.Timer might be what you're looking for. If you want help integrating it into your code, you should post that code here.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1390
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Variable reset

Postby timbo_cole » Mon May 20, 2013 9:19 pm

micseydel wrote:I'm not sure what metulburr meant about that, but I think that threading.Timer might be what you're looking for. If you want help integrating it into your code, you should post that code here.


I would like a maximum of one email an hour for each server so a maximum of 4 emails an hour all together!

Hi there, The code is below, please note that the following are placeholders: Hostname1, Hostname2, Hostname3, Hostname4, username, password, TO EMAIL ADDRESS, FROM EMAIL ADDRESS, USERNAME and PASSWORD.
Code: Select all
#!/usr/bin/python
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
from ftplib import FTP
import smtplib
import os



class MyHandler(FTPHandler):
    def on_file_received(self, file):
        file_name = os.path.basename(file)
        server_info = {'Hostname1': ('username', 'password'),   # Server 1
          ''.join(list('Hostname2')): ('username', 'password'),    # Server 2
          ''.join(list('Hostname3')): ('username', 'password'),   # Server 3
                       '192.168.1.112': ('username', 'password')}   # Server 4
        for server, info in server_info.iteritems():
            try:
                ftp = FTP(server)
                ftp.login(*info)
                ftp.storbinary('STOR ' + file_name, open(file, 'rb'))
            except:
      if server == 'Hostname1':
         server_name = 'Server 1'
         print server_name

      if server == 'Hostname2':
         server_name = 'Server 2'
         print server_name

      if server == 'Hostname3':
         server_name = 'Server 3'
         print server_name
         
      if server == 'Hostname4':
         server_name = "Server 4"
         print server_name
         
                fromaddr = 'TO EMAIL ADDRESS'
                toaddrs  = 'FROM EMAIL ADDRESS'
                text = server_name + ' is currently offline!'
                msg = 'Subject: %s\n\n%s' % ('FTP ERROR', text)
               

                # Credentials (if needed)
                username = 'USERNAME'
                password = 'PASSWORD'

                # The actual mail send
                server = smtplib.SMTP('smtp.gmail.com:587')
                server.starttls()
                server.login(username,password)
                server.sendmail(fromaddr, toaddrs, msg)
                server.quit()

                print "Email Sent"
                continue
        os.remove(file)



def main():
    # Instantiate a dummy authorizer for managing 'virtual' users
    authorizer = DummyAuthorizer()

    # Define a new user having full r/w permissions and a read-only
    # anonymous user
    authorizer.add_user('USERNAME', 'PASSWORD', 'FILE PATH', perm='elradfmw')



    # Instantiate FTP handler class
    handler = MyHandler
    handler.authorizer = authorizer

    # Define a customized banner (string returned when client connects)
    handler.banner = "Welcome to the Photo Distribution Server"

    # Specify a masquerade address and the range of ports to use for
    # passive connections.  Decomment in case you're behind a NAT.
    #handler.masquerade_address = '151.25.42.11'
    #handler.passive_ports = range(60000, 65535)

    # Instantiate FTP server class and listen on 0.0.0.0:2121
    address = ('', 21)
    server = FTPServer(address, handler)

    # set a limit for connections
    server.max_cons = 300
    server.max_cons_per_ip = 20

    # start ftp server
    server.serve_forever()

   
   

if __name__ == '__main__':
    main()
timbo_cole
 
Posts: 9
Joined: Fri May 17, 2013 8:12 pm

Re: Variable reset

Postby metulburr » Mon May 20, 2013 10:08 pm

i was talking about cron tab. Which you have a script to send out email or do whatever. If you want that script auto ran at midnight every day, you could use a cron job to execute that script at midnight. which would be:
Code: Select all
00 00 * * * python your_script_name.py

where 00's mean 0 minutes and 0 seconds, the the *('s) mean every day of every month

There is a cronjob for windows, but dont know the process. In linux, the crontab file example would be:
Code: Select all
metulburr@ubuntu:~$ crontab -l
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#

#Instead of the first five fields, one of eight special strings may appear:
#string         meaning
#------         -------
#@reboot        Run once, at startup.
#@yearly        Run once a year, "0 0 1 1 *".
#@annually      (same as @yearly)
#@monthly       Run once a month, "0 0 1 * *".
#@weekly        Run once a week, "0 0 * * 0".
#@daily         Run once a day, "0 0 * * *".
#@midnight      (same as @daily)
#@hourly        Run once an hour, "0 * * * *".
# m h  dom mon dow   command

# Minute   Hour   Day of Month       Month          Day of Week        Command   
# (0-59)  (0-23)     (1-31)    (1-12 or Jan-Dec)  (0-6 or Sun-Sat)     

@reboot python3 /home/metulburr/Documents2/ipchecker.py
*/1 * * * * python3 /home/metulburr/Documents2/ipchecker.py
 
metulburr@ubuntu:~$


If your looking for every hour to execute a job. The line would be:
Code: Select all
0 * * * * python your_script_name.py


but i guess you could do it programmatically with threading.Timer too.
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1476
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Variable reset

Postby micseydel » Mon May 20, 2013 10:24 pm

metulburr, he was saying he wanted to modify the state of a running program at a specific time, not launch a new program.

OP: you're driving me nuts with that server_info definition. ''.join(list(any_string)) is always just any_string. So that variable should just be
Code: Select all
server_info = {
   'Hostname1': ('username', 'password'),
   'Hostname2': ('username', 'password'),
   'Hostname3': ('username', 'password'),
   '192.168.1.112': ('username', 'password')
   }

Wanting a specific variable to reset once a day is different from what you want, I don't think you need threading.Timer. I'm not sure what the best way to do it is, but I would think you would call a method that puts the emails in a queue and then some worker thread would send the emails.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1390
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Variable reset

Postby metulburr » Mon May 20, 2013 10:42 pm

well with the OP's initial question:
I was thinking 2 scripts. The program itself checking the data of a file for being the value of 0, then if it is, reset that value to 1, then do its thing, and then keep checking for 0 again. While the other script is just resetting that value to 0, where being on a cron job this script only gets executed at midnight. So hence the program does whatever it needs to do at midnight.

With his second post showing more about what he is doing, I would be thinking of something different. To have a script that emails upon execution. And just having a cronjob execute that script upon a specified time.
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1476
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Variable reset

Postby timbo_cole » Mon May 20, 2013 10:52 pm

Sorry for the concussion, I was thinking and would I be able to extract the minute integer, if so, I could say is minute = 00 then variable = 0

And only send the email if variable = 0, as well as adding variable = 1 at the end of the email code.

Would this be possible - the crontab won't work as the email only sends in the case that there is an error in connecting to an FTP server.

Would this be possible/work?
timbo_cole
 
Posts: 9
Joined: Fri May 17, 2013 8:12 pm

Re: Variable reset

Postby metulburr » Mon May 20, 2013 11:15 pm

I found this method. This may work programmatically.

Code: Select all
import time
while True:
    if time.strftime("%M") == "00":
        print("Do Whatever you want here")
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1476
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Variable reset

Postby timbo_cole » Tue May 21, 2013 9:51 am

metulburr wrote:I found this method. This may work programmatically.

Code: Select all
import time
while True:
    if time.strftime("%M") == "00":
        print("Do Whatever you want here")

Hi,
I have experimented with this code in a separate document:
Code: Select all
import time

variable = 1

while True:

    print variable
    if time.strftime("%M") == "48" and time.strftime("%S") == "00":
        variable == 0


But it changes to 0 for a second and then changes back to 1 (even thought the declaration of 1 is not in the loop). Any ideas?
timbo_cole
 
Posts: 9
Joined: Fri May 17, 2013 8:12 pm

Re: Variable reset

Postby timbo_cole » Tue May 21, 2013 10:03 am

Sorted, the code should have been like this:
Code: Select all
import time

variable = 1

while True:

    print variable
    if time.strftime("%M") == "48" and time.strftime("%S") == "00":
        variable = 0
timbo_cole
 
Posts: 9
Joined: Fri May 17, 2013 8:12 pm

Re: Variable reset

Postby Kebap » Tue May 21, 2013 12:14 pm

Thanks for reporting back. Looking back, this thread seems a bit hindered by the way you ask your questions. Maybe try and describe the goal, not the step
Learn: How To Ask Questions The Smart Way
Join the #python-forum IRC channel on irc.freenode.net and chat with uns directly!
Kebap
 
Posts: 396
Joined: Thu Apr 04, 2013 1:17 pm
Location: Germany, Europe


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 5 guests