×
Namespaces

Variants
Actions

Archived:Python on Symbian/03. System Information and Operations

From Nokia Developer Wiki
Jump to: navigation, search

Archived.pngAquivado: Este artigo foi arquivado, pois o conteúdo não é mais considerado relevante para se criar soluções comerciais atuais. Se você achar que este artigo ainda é importante, inclua o template {{ForArchiveReview|escreva a sua justificativa}}.

All PySymbian articles have been archived. PySymbian is no longer maintained by Nokia and is not guaranteed to work on more recent Symbian devices. It is not possible to submit apps to Nokia Store.

Article Metadata
Article
Created: hamishwillee (29 Nov 2010)
Last edited: hamishwillee (08 May 2013)

Original Authors: Pankaj Nathani and Mike Jipping

Having covered the basic Python conventions and coding syntax in Chapter 2, it's time to move on to discuss how to use Python on Symbian. This chapter describes how to access device and application information, how to perform system operations and how to work with files and time values.

This chapter introduces sysinfo and e32, the modules that provide information about the device and the current application respectively. The e32 module also contains utilities to perform system operations, such as running and pausing scripts and setting the device time.

Finally, the chapter discusses core functionality inherited from standard Python, such as how to perform operations related to time and how to manipulate files. It covers Symbian's file naming and handling conventions and shows how Python handles files in ways similar to other programming languages.

The methods described in this chapter are frequently used in Python applications for Symbian devices, including many of the examples in this book.

Contents

The System Information Module

The sysinfo module can be used to access the following device information:

  • IMEI
  • signal strength
  • battery strength
  • firmware version
  • OS version
  • screen display resolution
  • current profile
  • current ringing type
  • RAM and ROM drive size
  • the amount of free RAM, ROM and disk drive space.

The module is easy to use. For example, the following two lines in the interactive PySymbian console return the IMEI of the device:

>>>import sysinfo
>>>sysinfo.imei()
u’2174027202720292

Note.pngNote: Every mobile device on a GSM network is identified by a unique number called its IMEI (International Mobile Equipment Identity), about which you can find out more from http://en.wikipedia.org/wiki/International_Mobile_Equipment_Identity.
The IMEI of the device can be retrieved manually by dialing *#06#.

The following code snippets show the methods used to obtain the information and their return types.

# Retrieve battery strength as an integer. The value is in the range 0 (empty) to 100 (full). 
>>> sysinfo.battery()
42
 
# Retrieve signal strength as an integer. The value is in the range 0 (no signal) to 7 (strong signal).
>>> sysinfo.signal_bars()
7
 
# Retrieve network signal strength in dBm (integer)
>>> sysinfo.signal_dbm()
81
 
# Retrieve the IMEI code of the device as a Unicode string
>>> sysinfo.imei()
u'354829024755443'
 
# Retrieve the software version as a Unicode string. This is the version number that a device displays when *#0000# is dialled.
>>> sysinfo.sw_version()
u'V 20.0.016 28-2-08 RM-320 N95(c)NMP'
 
# Retrieve the width and height of the display (in the current orientation) in pixels
>>> sysinfo.display_pixels()
(240, 320)
 
# Get the current profile name as a string ('general', 'silent', 'meeting', 'outdoor', 'pager', 'offline', etc). If a custom profile is selected - it returns 'user <profile value>'
>>> sysinfo.active_profile()
'general'
 
# Retrieve the ringing type as a string - 'normal', 'ascending', 'ring_once', 'beep' or 'silent'
>>> sysinfo.ring_type()
'normal'
 
# Get the OS version as a tuple
>>> sysinfo.os_version()
(2, 0, 1540)

Note.pngNote: When running on the emulator some of the functions return dummy values:

  • battery() and signal_bars() return 0.
  • sw_version() returns u’emulator’
  • imei() returns u’0000000000000000’

Symbian devices usually have an internal disk (C:) and a memory card (E:). If there is a random access memory (RAM) drive it is mapped to D: and Z: is the read only memory (ROM) drive. There are exceptions: some devices use E drive for 'internal' mass memory and some have additional drives. The amount of ROM, RAM and disk space varies across devices.

sysinfo can also return information about the device memory, shown as follows:

# Get free RAM in bytes
>>> sysinfo.free_ram()
81838080
 
# Get total RAM in bytes
>>> sysinfo.total_ram()
125501440
 
# Get total ROM in bytes
>>> sysinfo.total_rom()
8716288
 
# Get free disk space in bytes. Drive can be C: or E:
>>> sysinfo.free_drivespace()['C:']
16207872

Note that the e32 module provides drive_list() to get the list of drives, as discussed in the following section.

The e32 Module

The e32 module contains a useful and varied collection of utilities. The utilities range from methods that retrieve information about the device and current application, to methods that pause the current script or reset the device inactivity timer. There are also methods available for filesystem operations, such as copying files and folders.

The e32 module provides the following 'system' information in addition to that provided by sysinfo:

  • The Python runtime version
  • The Symbian device runtime version
  • The list of available drives
  • The platform security capabilities of the current application
  • The length of time since the last user activity
  • Whether or not the current thread is a UI thread
  • Whether or not the current application or script is running on an emulator

The code snippet below shows the methods used to obtain the above information.

# Get the Python runtime version - tuple of version number: major, minor, micro and release tag,
>>> e32.pys60_version()
(1, 9, 7, 'svn2793')
 
# Get the Python runtime version - tuple of major, minor, micro, release tag, and serial.
>>> e32.pys60_version_info()
(1, 9, 7, 'svn2793', 0)
 
# Get the Symbian platform device version - tuple of major and minor version
>>> e32.s60_version_info()
(3, 0)
 
# Retrieve a list of available memory drives. For example: [u'C:',u'D:',u'E:',u'Z:']
>>>e32.drive_list()
[u'C:',u'D:',u'E:',u'F:',u'Z:']
 
# Get the time in seconds since the last user activity
>>> e32.inactivity()
3
 
# Get the platform security capabilities granted to the application, returned as a tuple
>>> e32.get_capabilities()
('ReadUserData','WriteUserData')
 
# Test if application has been granted the specified platform security capabilities. Returns True or False.
# querying single capability
>>> e32.has_capabilities('WriteUserData')
True
 
# Query whether the application has two capabilities
>>> e32.has_capabilities('WriteUserData','ReadUserData')
True
 
# Test if the calling script is running in the context of a UI thread. Returns True or False
>>> e32.is_ui_thread()
True
 
# Test whether or not the application or script is running in an emulator. Returns 1 if yes, 0 if no.
>>>e32.in_emulator()
1


The e32 module can perform the following system operations on the device.

Set the device's system time

The set_home_time() function sets the device system time to given time (for e.g. user_time in the example below). The device system time can be retrieved through the time module as explained in next section.

import e32
import time
 
# current time
user_time = time.time()
# modify the user_time
user_time -= 10.0
 
e32.set_home_time(user_time)

Note.pngNote: The WriteDeviceData capability is required to use this function. For more information, refer to Chapter 15.

Copy files

The file_copy() function can be used to copy files from one folder to another.

>>> source_path=u"C:\\Python\\myimage.jpg"
>>> destination_path=u"C:\\Data\\Images\\myimage.jpg"
>>> e32.file_copy(destination_path,source_path)

To copy all of the files in the source folder append '*.*' to the source path.

>>> source_path=u"C:\\Python\\*.*"
>>> destination_path=u"C:\\Data"
>>> e32.file_copy(destination_path,source_path)

This copies all the files in the C:\Python directory to the C:\Data directory.

Note.pngNote: 

  • Double backslashes '\\' must be used to specify directory paths
  • The destination directory must already exist - the function fails if it doesn't.
  • If the copy operation fails, it throws an exception

Launch an application

The start_exe() method can be used to launch a specified executable (.exe) file, as follows.

>>> e32.start_exe(exe_filename, command, wait_flag)

The parameter command passes command line arguments to the executable. If no arguments are required, it may be set to NULL or an empty string. The parameter wait_flag is an optional parameter as described below.

The following statement is used to launch the Web browser with the default URL, and the command parameter is passed an empty string.

 >>> application_exe='BrowserNG.exe'
>>> a=e32.start_exe(application_exe, "")

In order to open the web browser application with a particular URL, we pass it as a command as follows.

>>> url="http://licensing.symbian.org/"
>>> application_exe='BrowserNG.exe'
>>> e32.start_exe(application_exe, ' "%s"' %url)

In both the previous examples the browser is launched asynchronously. We can use the optional wait_flag integer parameter to launch an application synchronously.

If a non-zero value is specified for wait_flag then start_exe() launches the application and waits for it to exit. It then returns 0 if the application exits normally or 2 if the application terminates abnormally.

>>> wait_flag=1
>>> url="4 http://licensing.symbian.org/"
>>> exit_type=e32.start_exe(application_exe,' "%s"' %url, wait_flag)
>>> print exit_type

The '4 ' prefix in the url parameter indicates that the browser should launch the url specified. Other predefined prefixes for the parameter are shown below:

Prefix Parameter Description
None <Any text> Start (or continue) the browser with no specified content
1 ”<Space>“+”<Uid of a bookmark>” Start or continue the browser with specified bookmark
2 ”<Space>“+”<Uid of a saved deck>” Start or continue the browser with specified saved deck
4 ”<Space>“+”<URL>” Start or continue browser with specified URL
4 ”<Space>“+”<Url>”+”<Space>“+”<Uid of AP>” Start or continue the browser with specified bookmark and Access Point (AP)
5 <Any text> Start or continue the browser with the start page.
(Used when starting the browser with a long press of “0” in the Idle state of the phone)
6 ” <Space>“+”<Uid of bookmark folder>” Start or continue the browser with specified bookmark folder


The start_exe() function can also be used to launch other native and third party applications.

Launch a python script as a server

A Python script can be launched in the background (as a server script) with the start_server() function.

>>> server_script.py=u"C:\\Data\\Python\\myscript.py"
>>> e32.start_server(server_script)

Note.pngNote: The appuifw module cannot be used in a Python server script.

Reset inactivity timer

The reset_inactivity() method can be used to reset the inactivity timer programmatically .

>>> e32.reset_inactivity()

Resetting the inactivity timer at regular intervals prevents the device from entering a low power mode during periods of user inactivity. This can be useful if an application needs to remain visible when the user is not "doing anything" - for example, when using an in-car hands-free navigation system. See also inactivity(), which returns the current value of the inactivity timer.

Wait/Sleep

Note.pngNote: Active objects are used extensively in Symbian C++ to provide co-operative multitasking to applications and other code. The concept is used to implement much of Python's underlying behaviour on Symbian and, for this reason, many function names in Python on Symbian have an ao_ prefix.
Active objects are discussed in detail elsewhere (e.g. in the Symbian C++ Reference Library).

ao_sleep()

The ao_sleep() method can be used to introduce a delay between the execution of statements, or to call a specified method after a given interval. The use of ao_sleep() is encouraged over the standard time.sleep() method (documented at http://docs.python.org/library/time.html#time.sleep), because ao_sleep() doesn't block the active scheduler, which means that the UI can remain responsive.

For example, the following code causes the script to wait for two seconds.

print "Waiting for 2 seconds"
e32.ao_sleep(2) #sleeps for 2 seconds
print "Wait over"

A call back function can be specified when calling ao_sleep(). In the example below, the function foo() is called after 3 seconds.

def foo():
print "In function"
 
e32.ao_sleep(3,foo)


ao_yield() and ao_callgate()

Calling ao_yield() gives control back to the active scheduler, thereby allowing any active object-based code with priority above normal to run. In practice this keeps an application responsive to menu and softkey input, even while performing other long running events. For example, the following code fragment displays notes within a continuous while loop. The use of e32.ao_yield() ensures that we can exit the loop (and application) by pressing the right soft key. Without e32.ao_yield() in the loop, the active scheduler would never get to run the event handling code.

def quit():
global running
running=0
appuifw.app.set_exit()
 
appuifw.app.exit_key_handler=quit
 
running=1
 
while running:
appuifw.note(u"hello")
e32.ao_yield()


The ao_callgate() method creates an active object wrapper around a callable Python function and returns another function object that can be used to start the active object. The original Python function will be called at some point after the wrapper function is called when its associated active object is run by the active scheduler. The wrapper object can be used to call the function from any Python thread; the function is run 'in the context of the thread where the ao_callgate() was created'.

The following example shows how the function fun() is registered with the callgate to return the wrapper object foo(). Method fun() is run by the active scheduler at some point after foo() is called.

import e32
 
def fun():
print "Hello"
 
foo = e32.ao_callgate(fun)
foo()


Ao_lock and Ao_timer

Two important classes defined in the e32 module are Ao_lock and Ao_timer. They are classes, unlike the operational functions above, so they can only be used after they have been instantiated.

Ao_lock is an active object-based synchronization service that is at the heart of the Python application UI structure as Chapter 4 describes. An Ao_lock object is used by creating an instance of Ao_lock, adding a number of active objects, and then calling wait() on the thread, shown as follows:

#Create instance of Ao_lock
app_lock = e32.Ao_lock()
 
# Add active objects here - e.g. menu callbacks
...
 
#Wait for application lock to be signaled
app_lock.wait()

Python halts execution of the script at the wait, but any active objects that are already running will be serviced. Python implements menus as active objects, so they are still called and the UI remains responsive. When you're ready to continue execution of the script you call signal(). However, as the script execution is halted at the wait() you must signal it to restart through a menu callback. It is a convention to release the waiting script in the quit() function:

#Signals the lock and releases the "waiter"
def quit():
app_lock.signal()

Remember that wait() can only be called in the thread that created the lock object and only one "waiter" is allowed, so take care when using it in a loop.

Ao_timer is a Symbian active object-based timer service. Like Ao_lock, it can be used in the main thread without blocking the handling of UI events. The following code snippet creates an instance of Ao_timer and illustrates use of its after() and cancel() methods.

#Create instance of Ao_timer
timer = e32.Ao_timer()
 
#Sleep for the 1 second without blocking the active scheduler and call the callback_function() (user defined callback)
timer.after(1, callback_function)
 
#Cancels the 'after' call.
timer.cancel()


The callback function parameter of the after() method is optional; if it is not specified the thread simply sleeps for the specified time.

The cancel() method can be used to cancel a pending after() request. It is important to cancel pending timer calls before exiting the application. If you forget, the application will panic on exit.

Tip.pngTip: Use Ao_timer instead of ao_sleep() where possible, because a pending ao_sleep() cannot be canceled, which means that a user cannot exit the application while the application is sleeping.

Time Operations

Python's concept of time comes from the Unix operating system. Unix measures time as the number of seconds since the epoch, which started on January 1, 1970 at 00:00:00 UTC (also known as Greenwich Mean Time). For example, midnight on 1 January 2010 was 1,262,304,000 seconds since the Unix epoch.

Tip.pngTip: Generally speaking you don't need to think about the number of seconds! Python provides methods to allow you to convert to more friendly units. If you do need to do a manual conversion, there are several sites on the Internet that will convert them for you:

There are several system functions that display and manipulate system time. Before we look at them, however, we should review the possible values accepted for time values. There are two sets of values:

  1. float values represent seconds since the epoch as described above (the float data type must be used because this number of seconds is large).
  2. time structure values are nine integers that correspond to specific time components, as shown in the table below:


Python Name Description
tm_year four digit value depicting the year
tm_mon integer in the range 1 to 12 depicting the month
tm_mday integer in the range 1 to 31 depicting the day of the month
tm_hour integer in the range 0 to 23 depicting the hour
tm_min integer in the range 0 to 59 depicting the minute
tm_msec integer in the range 0 to 61 depicting the second (the 60th and 61st values account for leap and double leap seconds)
tm_wday integer in the range 0 to 6 depicting the day of the week (Monday has the value 0)
tm_yday integer in the range 0 to 365 depicting the day of the year (accommodating for leap year)
tm_isdst integer in the range 0 to 1 depicting a boolean value to determine Daylight Savings Time (can be -1, see mktime() below,

For example, consider the code below, where time.localtime() returns the time structure values as a tuple:

import time
(a,b,c,d,e,f,g,h,i) = time.localtime()

If this code were executed on 8 September 2009, at 9:15:38 am, then the variables would have the following values:

   a = 2009
   b = 9
   c = 8
   d = 9
   e = 15
   f = 38
   g = 1
   h = 251
   i = 1

Let's briefly overview the functions in the time module:

  • time.asctime([t]) converts the time - either the current time, if the parameter is absent, or the time represented by the optional tuple representing a time structure value - to a string that depicts the time described.
  • time.clock() returns the current processor time as a float in seconds. You cannot really depend on this value for anything other than comparative uses.
  • time.ctime([secs]) converts a time value in seconds since the epoch to a time structure value UTC. For this conversion, the dst flag is always zero, which means adjustment for Daylight Savings Time is not done. If secs is not provided or is None, the current time as returned by time() is used.
  • time.gmtime([secs]) converts a time expressed in seconds since the epoch to a time structure value in UTC in which the dst flag is always zero. If secs is not provided or None, the current time is used.
  • time.localtime([secs]) converts to local time, returning a time structure value. If secs is not provided or is None, the current time is used.
  • time.mktime(t) can be viewed as the inverse function of localtime(). Its argument is a tuple depicting a time structure value, which expresses the time in local time, not UTC. It returns a floating point number of seconds since the epoch. If the input value cannot be represented as a valid time, either OverflowError or ValueError is raised.
  • time.sleep(secs) suspends execution of the current program for the given number of seconds. This number may be a floating point number to indicate a precise sleep time.
  • time.strftime(format[, t]) converts a tuple representing a time structure value to a string as specified by the format argument. If t is not provided, the current time is used. format must be a string. A ValueError exception is raised if any field in t is outside of the allowed range. More on this function below.
  • time.strptime(string[, format]) parses a string representing a time according to a format. The return value is a time structure value. The format follows the same directives as strftime(), which are described below.
  • time.time() returns the time as a floating point number expressed in seconds since the epoch, in UTC.
  • time.tzset() resets the time conversion rules used by the library routines. The environment variable TZ specifies how this is done.

The strftime() and strptime() functions use special directives embedded in a format string. These directives are shown below:

Directive Description
%a abbreviated weekday name
%A full weekday name
%b abbreviated month name
%B full month name
%c date and time representation appropriate for region
%d day of the month as an integer
%H hour as an integer on the 24-hour clock
%I hour as an integer on the 12-hour clock
%j day of the year as an integer
%m month as an integer
%M minute as an integer
%p AM or PM as a string
%S seconds as an integer
%U week number of the year as an integer (with Sunday considered the first day of the week)
%w weekday as an integer (Sunday is day numbered 0)
%W week number of the year as an integer (with Monday considered the first day of the week)
%x date representation as a string
%X time representation as a string
%y year as an integer without century
%Y year as in integer with century
%Z time zone name (no characters if no time zone exists)

Here are some examples. Consider the following code:

time.strftime("Now is %a, %d %b %Y at %H:%M:%S", time.gmtime())

This format string combines regular text with time specifiers. It also gets the time value from time.gmtime(). This code produces the output:

Now is Wed, 09 Sep 2009 at 13:58:37

Now consider this code:

thedate = "31 Dec 08"
t = time.strptime(thedate, "%d %b %y")
if t[7] == 366:
print thedate, "was in a leap year"
else:
print thedate, "was not in a leap year"

In the above example, the results showed that 2008 was a leap year, because '31 Dec 08' was day number 366 in the year. Notice that the format string for time.strptime() describes the way that the first string depicting the date is formatted.

There are also some variables represented in the time module. These are:

  • time.accept2dyear is a boolean value indicating whether two-digit year values will be accepted.
  • time.altzone represents the offset of the local DST timezone, in seconds west of UTC, if one is defined.
  • time.daylight is nonzero if a DST timezone is defined.
  • time.timezone is the offset of the local timezone, in seconds west of UTC.
  • time.tzname is a tuple of two strings. The first is the name of the local timezone; the second is the name of the local DST timezone.

Note.pngDoes this look familiar?: These calls and variables may look familiar. Python is based heavily on C and C++, so you might have recognized these methods as Unix system calls. The time structure values are also taken from Unix system calls. In fact, there is one more method - struct_time() - that works with the time values in the C struct time structure (see the struct values in the table above). Though you do not need to use it, most time methods accept a structure in the C form, much like this:

time.struct_time(tm_year=2010, tm_mon=0, tm_mday=0, tm_hour=0, tm_min=0,tm_sec=0, tm_wday=6, tm_yday=0, tm_isdst=-1)

The description here is of the system time module. There are other modules that provide a less primitive, more object-oriented approach to dates and times:

  • The datetime module generally handles dates and times.
  • The locale module implements internationalization services; its settings can alter the return values for some of the functions above.
  • The calendar module implements calendar related functions.

Finally, there is one more system function we should look at: e32.set_home_time(). This call comes from the e32 module and is used to set the current time for the device. The parameter required is the time, to be set in Unix 'seconds past the epoch' format. For example:

import e32
 
e32.set_home_time(1262304000)

This code sets the global device time to midnight on 1 January 2010.

To execute the code, an application requires the WriteDeviceData platform security capability. Capabilities are discussed in Chapter 15.

File Operations

As we discuss in Chapter 2, a file is a built-in data type for Python. Python handles files in ways similar to other programming languages. There are also some extended file operations in the modules unique to Python on the Symbian platform.

We'll start with the file naming conventions for the Symbian platform. Symbian uses conventions similar to those used in Microsoft Windows. Drive letters are used to indicate storage units such as memory or SD cards, there is a hierarchy of directories, and pathname components are separated by backslashes.

The following table outlines some of the common file operations provided by Python.

Operation Description
{{{1}}} Create a new file (the 'w' flag is for writing)
{{{1}}} Open the file for reading (the 'r' flag, for reading, is the default flag)
{{{1}}} Read the entire contents of a file into a single string variable
{{{1}}} Read "count" bytes into a string
{{{1}}} Read a single line into a string (includes end-of-line marker)
{{{1}}} Read the entire contents of a file into a list of strings, each holding a line
log.write(someContent) Write a string into a file
log.writeLines(stringList) Write a sequence of strings to the file (does not add end-of-line markers)
log.flush() Flush the buffer holding data for a file into that file
log.truncate() Cut off the file at the current position, discarding all data after that position
log.seek(position) Move the current position in a file to 'position'
log.close() Close a file


Most of these operations are similar to those used in other languages and platforms. Because of the way Python organizes data objects, some are more streamlined, such as the readlines() and writelines() functions, which make reading or writing a large amount of content quite easy.

Consider the following code:

html = ["<HEAD>"]
## ... generate HTML and append it to the list using "html.append(...)"
htmlfile = open("E:\Images\announce.html", "w")
htmlfile.writelines(html)
htmlfile.close()

Languages like Java would require each line of HTML to be written separately to a file, probably using a for loop. Here, however, one statement writes all lines to the file.

Note that data is always retrieved from files as a string - even non-readable data. This means that if you need data in another form, say numbers, you have to convert the data from strings to the form you need. Likewise, writing data to a file is always done using strings. Even if you want to write integers or floats, you must format the data into a string first, then write that string to a file. For example:

line = str(10) + "," + str(data) + "," + str(value) + "\n"
out.write(line)

This code builds three data items into a single string for writing. Likewise, we might read this data like

line = input.readline()
pieces = line.split(',')
data1 = int(pieces[0])
data2 = int(pieces[1])
converter = float(pieces[2])

Here we read a comma separated line, split it into pieces and convert the individual strings into the type of data we need.

We can also use some string formatting to construct the line we need for a file. Consider the following example, which rewrites the previous code:

line = "%d,%d,%f\n" % (10, data, value)
out.write(line)

The code works for simple data types, but native Python objects might be harder to convert to strings and back. This is where the pickle module comes in. The pickle module contains methods that allow almost any Python object to be written to a file (on S60 only tuples, lists and dictionaries are supported), with no conversion to and from strings. Consider the example below:

import pickle
dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
dictFile = open('dictfile', 'w')
pickle.dump(dict, dictFile)
dictFile.close()

The code allows the data store in the dictionary dict to be stored in the file 'dictfile' as a native Python dictionary. We can get the dictionary back using the code below:

infile = open('dictfile')
newdict = pickle.load(infile)
infile.close()

Now the variables dict and newdict have the same value.

In addition to these basic file operations, the os module has many file descriptor and directory operations. The file descriptor operations reveal the Unix operating system method of dealing with files. Unix uses integers to keep track of files at the system level (really indexes into a file table) and there are several primitive operations that work with these descriptors. There are useful operations to retrieve status information for files from the operating system. You can get more information at http://pys60.garage.maemo.org/doc/lib/os-fd-ops.html about file descriptors.

Many directory operations in the os module also deal with system-level manipulation of the file system, but some can prove useful in general use, including the following:

  • chdir(path) changes the current working directory of the application. This is useful, for example, when many files are manipulated and long pathnames are undesirable.
  • getcwd() retrieves the current working directory.
  • chmod(path, mode) changes the mode of the path given. The mode of a file is a set of permission flags kept by the operating system. Please refer to the list of permissions on http://pys60.garage.maemo.org/doc/lib/os-file-dir.html to understand everything you can change for a file.
  • listdir(path) returns a list of names for the files and directories in the directory specified as a parameter.
  • mkdir(path[, mode]) creates a directory with the pathname given and the (optional) permissions given by mode. Without the permissions given, the directory is created with all permissions for all users.
  • remove(path) deletes the file specified by path. If you specify a directory, Python raises an exception.
  • rename(src, dst) renames src to dst.
  • rmdir(path) removes the directory given by path.
  • stat(path) returns (a lot of) information about the path specified. See http://pys60.garage.maemo.org/doc/lib/os-file-dir.html for a complete list.
  • tempnam([dir[, prefix]]) returns a unique path name that can be used for creating a temporary file.

There are several additional file system-related calls available in the e32 and sysinfo modules that can be useful.

System Call Module Description
drive_list() e32 Returns a list of visible, accessible drives
file_copy(target_name, source_name) e32 Copies a file from target_name to source_name
free_drivespace() sysinfo Returns the amount of free space left on drives as a dictionary object using drive/space pairs

More information can be found at http://pys60.garage.maemo.org/doc/s60/node10.html and http://pys60.garage.maemo.org/doc/s60/module-sysinfo.html.

Summary

This chapter describes the system operations and information provided by two basic PySymbian modules: e32 and sysinfo, such as how to perform operations related to time, and how to work with files and directories. To cover a lot of ground quickly, we've used some rather simplistic examples, however we believe these are still very illustrative!

These features are combined with other ingredients of PySymbian in many of the examples in forthcoming chapters. We suggest you to use this chapter as a reference and come back to it whenever you need to apply these concepts in practice.

Licence icon cc-by-sa 3.0-88x31.png© 2010 Symbian Foundation Limited. Portions copyright Bogdan Galiceanu, Hamish Willee, Marcelo Barros de Almeida, Mike Jipping, Pankaj Nathani and others in wiki document history list. This document is licensed under the Creative Commons Attribution-Share Alike 2.0 license. See http://creativecommons.org/licenses/by-sa/2.0/legalcode for the full terms of the license.
Note that this content was originally hosted on the Symbian Foundation developer wiki.

This page was last modified on 8 May 2013, at 14:41.
110 page views in the last 30 days.