Python

Python

Explore python code snippets and tutorials

Python

Python date generator

python date generator

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import datetime
date = datetime.datetime.now()
time = date.time()
def date_generator(date, delta):
  counter =0
  date = date - datetime.timedelta(days=delta)
  while counter <= delta:
    yield date
    date = date + datetime.timedelta(days=1)
    counter +=1

for date in date_generator(date, 30):
   if date.date() != datetime.datetime.now().date():
     start_date = datetime.datetime.combine(date, datetime.time())
     end_date = datetime.datetime.combine(date, datetime.time.max)
   else:
     start_date = datetime.datetime.combine(date, datetime.time())
     end_date = datetime.datetime.combine(date, time)
   print('start_date---->',start_date,'end_date---->',end_date)
Python

create backup with python 3 one archive

create backup with python 3 one archive

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import os
import datetime
import subprocess
import shutil
import errno
from pathlib import Path


home = str(Path.home())
now = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
date_string = "{}".format(now)


dest = ''
'''
    dest var used to move created archives to another location
    example : dest = '/media/disk/'
'''
#dest = '{}/backup'.format(home)
'''
    folders is a list of folder paths to backup
    for example

    folders = [
        '/var/www/',
        '.ssh'
    ]
'''
folders = [
    
]

try:
    if dest is not None:
        os.makedirs(dest)
except OSError as e:
    if e.errno == errno.EEXIST:
        print('Directory not created.')
    else:
        raise
archived_name = "backup_{}.tar.gz".format(date_string)
print('create archive for folder :', archived_name)
out = subprocess.Popen(['tar','--use-compress-program=pigz','-cvf', archived_name ] + folders,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.STDOUT)
stdout, stderr = out.communicate()
archive_exists = os.path.exists("{}/{}".format(home, archived_name))
if archive_exists:
    print('archive {} created '.format(archived_name))
if dest:
    if archived_name:
        filename = "{}/{}".format(home, archived_name)
        shutil.move(os.path.join(
            home, archived_name), os.path.join(dest, archived_name))
Python

Python script to create a django project

Python script to create a django project

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import os
import argparse


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("-n", "--name", required=True,
                    help="name of the project")
    args = vars(ap.parse_args())
    name = args["name"]
    path = os.getcwd()
    directory = "{}/sites/{}".format(path, name)
    if not os.path.exists(directory):
        os.mkdir(directory)
    os.chdir(directory)
    if not os.path.exists('public'):
        os.mkdir('public')
    os.system("""python3 -m venv env &&
              . {0}/env/bin/activate &&
              pip install django django-debug-toolbar django-extensions &&
              pip freeze > requirements.txt &&
              django-admin startproject {1} &&
              cd {1} &&
              mkdir static &&
              mkdir templates &&
              cd templates &&
              touch base.html &&
              touch index.html""".format(directory, name))
Python

Create backup with python 3 multiple archives

<p>Create backup with python 3 multiple-archives</p>

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import os
import datetime
import subprocess
import shutil
from pathlib import Path


home = str(Path.home())
now = datetime.datetime.now()
year = now.year
day = now.day
month = now.month
date_string = "{}_{}_{}".format(year, day, month)


#dest = '/media/disk1/backups/'
'''
	dest var used to move created archives to another location
	example : dest = '/media/disk/'
'''
dest = None


'''
	folders is a list of folder paths to backup
	for example

	folders = [
		'/var/www/',
		'.ssh'
	]
'''
folders = [

]


for folder in folders:
	archived_name = None
	exists = os.path.exists(folder)
	if exists:
		folder_path = folder
		archived_name = "backup{}{}.tar.gz".format(
			folder.replace('/', '_').replace('.',''), date_string)
	if archived_name:
		if not os.path.exists(archived_name):
			print('create archive for folder :', archived_name)
			out = subprocess.Popen(
				['tar', '--exclude', '{}/env'.format(folder),
			 	 '{}/virtualenv'.format(folder),
			 	 '{}/bower_components'.format(
				 	folder), '-zcvf', archived_name, folder],
				stdout=subprocess.PIPE,
				stderr=subprocess.STDOUT)
			stdout, stderr = out.communicate()
			archive_exists = os.path.exists("{}/{}".format(home, archived_name))
			if archive_exists:
				print('archive {} created '.format(archived_name))
	if dest:
		filename = "{}/{}".format(home, archived_name)
		shutil.move(os.path.join(
			home, archived_name), os.path.join(dest, archived_name))
Python

Find srid of a shapefile in python 3

Find srid of shapefile in python 3

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import urllib.parse
import urllib.request
import json
from osgeo import ogr, osr

prj_file = open('file.prj', 'r')
prj_txt = prj_file.read()
prj_file.close()

query = {
    'exact': True,
    'error': True,
    'mode': 'wkt',
    'terms': prj_txt}
webres = 'http://prj2epsg.org/search.json'
data = urllib.parse.urlencode(query).encode("utf-8")
req = urllib.request.Request(webres)
with urllib.request.urlopen(req, data=data) as f:
    jres = json.loads(f.read())
    if jres['codes']:
        srid = int(jres['codes'][0]['code'])
        print(srid)