Wednesday, 12 September 2012

Python script to get the RAM and available hard disk memory

Python uses ctypes module to abstract the hardware information. ctypes allows to call functions in dlls/shared libraries and has extensive facilities to create, access and manipulate simple and complicated C data types in Python - in other words: wrap libraries in pure Python. It is even possible to implement C callback functions in pure Python.

ctypes works on Windows, Windows CE, Mac OS X, Linux, Solaris, FreeBSD, OpenBSD


import ctypes
import platform
import os

class SysInfo:

    def __init__(self):

        self.totalRam, self.availRam = self.ram()
        self.totalRam = self.totalRam / (1048576)
        self.availRam = self.availRam / (1048576)



    def ram(self):
    try:
        kernel32 = ctypes.windll.kernel32
        c_ulong = ctypes.c_ulong
        class MEMORYSTATUS(ctypes.Structure):
            _fields_ = [
                ('dwLength', c_ulong),
                ('dwMemoryLoad', c_ulong),
                ('dwTotalPhys', c_ulong),
                ('dwAvailPhys', c_ulong),
                ('dwTotalPageFile', c_ulong),
                ('dwAvailPageFile', c_ulong),
                ('dwTotalVirtual', c_ulong),
                ('dwAvailVirtual', c_ulong)
            ]

        memoryStatus = MEMORYSTATUS()
        memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS)
        kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus))
        return (memoryStatus.dwTotalPhys, memoryStatus.dwAvailPhys)
    except , err;
        print "No ram found"



    def get_free_space(self,folder, format="GB"):
        """
            Return folder/drive free space
        """
    try:
        fConstants = {"GB": 1073741824,
                      "MB": 1048576,
                      "KB": 1024,
                      "B": 1
                      }
        if platform.system() == 'Windows':
            free_bytes = ctypes.c_ulonglong(0)
            ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))
            #return (int(free_bytes.value/fConstants[format.upper()]), format)
            return (int(free_bytes.value/1073741824), format)
        else:
            return (int(os.statvfs(folder).f_bfree*os.statvfs(folder).f_bsize/fConstants[format.upper()]), format)
    except , err;
        print "No hard disk found"
       
if __name__ == "__main__":
        sys = SysInfo()
        print "System Memory : %dMb total" % sys.totalRam
        print "Available System Memory  : %dMb free" % sys.availRam
        byteformat = "GB"
        drive = raw_input("Enter drive:")
        space,size =  sys.get_free_space(drive+":", byteformat)
        print space,size

Ant script to create zip using 7zip commands


<?xml version="1.0" encoding="UTF-8"?>

<project name="zip-test" default="zip-file" basedir=".">

<property name="project-name" value="test" />
<property name="folder-to-zip" value="D:\abc\*" />
<echo message = "${folder-to-zip}"/>

<target name="clean">
   <echo message="${project-name}.7z"/>
<delete file="${project-name}.7z" />
</target>


<target name = "zip-file">
   <echo message = "${folder-to-zip}"/>
<exec executable="7z.exe">
<arg value="a"/>
<arg line="-t7z ${project-name} ${folder-to-zip}"/>
</exec>
</target>
<target name="run" depends="clean" />

</project>

Django Error:1005 "Can't create table 'nameofdb.#sql-*****' errno: 121"

While trying to configure Merengue CMS + Django on Opensuse , I got stuck here. The instant I run the "python manage.py migrate" it started giving error (1005 "Can't create table 'nameofdb.#sql-*****' errno: 121" ).After checking INNODB(MySql engine) status I found out that it is because of violation of some Foreign Key constraints.
                                    As the Django uses MYISM as the default engine it was having problems migrating the tables in Mysql 5.5 as the default engine in Mysql 5.5 is INNODB.
After doing a lot of googling , the solutions I tried out are as follows:-
1). In the settings.py script
     DATABASE_OPTIONS={'init_command': 'SET storage_engine=INNODB',}.
     Though it didnot work out for me.
2). ALTER TABLE <tablename> ENGINE=INNODB;
     Though it is worst solution as it was having too many tables, but i did it after doing the migration, though it      started the server, but it showed 500 Internal server error.
3). The solution provided by the Django community https://code.djangoproject.com/wiki/AlterModelOnSyncDB. I copied the whole code in __init.py. But nothing changed.

After spending lot of time I am still trying to find out the solution. Folks do provide your solutions.

In the meantime I am switching to Mezannine:-)

Saturday, 8 September 2012

from django.core import management ImportError: No module named django.core

After doing a lot of research I found out the reason that this error comes because of the wrong way of installing Django. So , you need to follow my blog http://toolsdeve.blogspot.in/2012/09/setting-up-django-on-windows.html.

Setting Up Django on windows

As Django is entirely a  Python Web framework, Django requires Python.  It works with  Python versions from 2.5 to 2.7 (due to backwards incompatibilities in Python 3.0, Django does not currently work with Python 3.0).
Steps:-
1)  Install Python 2.5 or later from http://www.python.org.
2)  Remove any earlier version of Django you already have.
3) Download and Install the current version of Django from https://docs.djangoproject.com/en/1.4/misc/distributions/.
4) Open your command prompt
               >>>>>cd c:\django\bin> python setup.py install
5) Django folder will automatically be copied into your python\sitepackage folder.
              >>>>>cd C:\Python27\Lib\site-packages\django\bin> django-admin.py

If you get this:


Usage: django-admin.py subcommand [options] [args]

Options:
  -v VERBOSITY, --verbosity=VERBOSITY
                        Verbosity level; 0=minimal output, 1=normal output,
                        2=verbose output, 3=very verbose output
  --settings=SETTINGS   The Python path to a settings module, e.g.
                        "myproject.settings.main". If this isn't provided, t
                        DJANGO_SETTINGS_MODULE environment variable will be
                        used.
  --pythonpath=PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Print traceback on exception
  --version             show program's version number and exit
  -h, --help            show this help message and exit

Type 'django-admin.py help <subcommand>' for help on a specific subcommand.

Available subcommands:

[django]
    cleanup
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    runfcgi
    runserver
    shell
    sql
    sqlall
    sqlclear
    sqlcustom
    sqlflush
    sqlindexes
    sqlinitialdata
    sqlsequencereset
    startapp
    startproject
    syncdb
    test
    testserver
    validate
>>>you are done with your settings.....enjoy...:-)