Python OS/PDB module and Data Type Basics

Source: Internet
Author: User
Tags list of attributes

Import time

Time. Sleep (2) # Pause for 2 seconds

OS module:

OS. chkdir (PATH) is converted to the directory path.

OS. System ('md A') can directly create a directory.

The OS. Name string indicates the platform you are using. For example, for Windows, it is 'nt ', and for Linux/Unix users, it is 'posix '.
● The OS. getcwd () function obtains the current working directory, that is, the directory path of the current Python script.
● The OS. getenv () and OS. putenv () functions are used to read and set environment variables respectively.
● OS. listdir () returns all files and directory names under the specified directory.
● The OS. Remove () function is used to delete an object.
● The OS. System () function is used to run shell commands.
● The OS. linesep string provides the row Terminator used by the current platform. For example, in windows, '\ r \ n' is used, in Linux,' \ n' is used, and in MAC, '\ R' is used '.
● The OS. Path. Split () function returns the directory name and file name of a path.
>>> OS. Path. Split ('/home/swaroop/byte/code/poem.txt ')
('/Home/swaroop/byte/Code', 'poem.txt ')
● The OS. Path. isfile () and OS. Path. isdir () functions verify whether the given path is a file or a directory. Similarly, the OS. Path. exists () function is used to check whether the GIVEN PATH actually exists.

Exec statements are used to execute Python statements stored in strings or files. For example, we can generate a package at runtime.
A string containing Python code, and then execute these statements using exec statements. The following is a simple example.
>>> Exec 'print "Hello World "'
Hello World
The eval statement is used to calculate the valid Python expression stored in the string. The following is a simple example.
>>> Eval ('2*3 ')
6

 

If the py file new1.py already exists, enter new1> new.txt in the command line to export the result of new1runtime to new.txt, which is called Stream redirection.

1. the Dir () function displays a list of attributes, including many variables.

2. Run the del command to delete variables, such as del.

3. Create your own modules
#! /Usr/bin/Python
# Filename: mymodule. py
Def sayhi ():
Print 'Hi, this is mymodule speaking .'
Version = '0. 1'
# End of mymodule. py

4. reference the above Module

Import mymodule
Mymodule. sayhi ()
Print 'version', mymodule. Version

Running result:

# Filename: mymodule_demo.py

$ Python mymodule_demo.py
Hi, this is mymodule speaking.
Version 0.1:

Method 2:

# Filename: mymodule_demo2.py
From mymodule import sayhi, version
# Alternative:
# From mymodule import *
Sayhi ()
Print 'version', version

The results are the same.

5. List members are separated by commas (,) and sorted by the sort method of the list. This method affects the List itself, rather than returning a modified list-different from the method used to operate strings. This is what we call the list variable and the string variable. You can assign values to members and pass the values to another list. However, the target list must first initialize 0 to allocate memory units. A string cannot be assigned a value to a Member.

The list. Sort () function sorts data by size. Append adds a list member and del deletes the member, such as shoplist. append ('Member ') and del shoplist [subscript of the member]. Help (list. Sort)

• Insert (I, x) ---- insert an item at the specified position. The first independent variable is inserted before the element and is represented by a subscript. For example, if a. insert (0, x) is inserted before the list, A. insert (LEN (A), X) is equivalent to a. append (X ).

• Append (x) ---- equivalent to a. insert (LEN (A), X)

A. Extend (list) adds multiple elements.

• Index (x) ---- search for the value x in the list and return the subscript of the first element with the value x. An error occurred while not found.

• Remove (x) ---- Delete the first element with the value of X from the list. An error occurs when the element cannot be found.

• Sort () ---- sort list elements in the original position. Note that this method changes the list instead of returning the sorted list.

• Reverse () ---- sorts list elements in reverse order. Change the list.

• Count (x) ---- returns the number of times X appears in the list.
List () and tuple () can be converted between lists and tuples.

6. arrays and lists are very similar, except that arrays and strings are immutable, that is, you cannot modify arrays. The array is defined by commas (,) in parentheses. Arrays are usually used to securely use a group of values for statements or user-defined functions. That is, the values of the used arrays will not change.

Tuples that contain 0 or 1 project. An empty tuples consist of an empty pair of parentheses, such as myempty = (). However, tuples containing a single element are not that simple. You must be followed by a comma in the first (unique) project so that python can distinguish between a tuple and an object with parentheses in the expression. That is, if you want a tuples containing project 2, you should specify Singleton = (2 ,).

7. When printing, add a comma to print the same line, that is, no line break. The default line feed is not added.

8. array # filename: print_tuple.py
Age = 22
Name = 'swaroop'
Print '% s is % d years old' % (name, age)
Print 'Why is % s playing with that python? '% Name

9. The key-value pairs in the dictionary are marked as: D = {key1: value1, key2: value2} in this way }. Pay attention to the usage of key/value pairs.
And each pair is separated by a comma, all of which are included in curly brackets. Help (dict) query.

# Filename: using_dict.py
# 'AB' is short for 'A' ddress 'B' ook
AB = {'swaroop ': 'swaroopch @ byteofpython.info ',
'Larry ': 'Larry @ wall.org ',
'Matsumo': 'matz @ ruby-lang.org ',
'Spammer': 'spammer @ hotmail.com'
}
Print "swaroop's address is % s" % AB ['swaroop ']
# Adding a key/value pair
AB ['guid'] = 'guido @ python.org'
# Deleting a key/value pair
Del AB ['pemer']
Print '\ nthere are % d contacts in the address-book \ n' % Len (AB)
For name, address in AB. Items ():
Print 'Contact % s at % s' % (name, address)
If 'guid' in AB: # Or AB. has_key ('guid ')
Print "\ nguido's address is % s" % AB ['guid']

10. Sequence

Lists, arrays, and strings are sequences. The index operators and slice operators are two main features of sequences. The index operator allows us to capture a specific item from the sequence. The Slice operator allows us to obtain a slice of a sequence, that is, a part of the sequence.

11. References and objects

For the two sequences A, B. A = B and A = B [:] are different, the latter is a copy, and the former is two variables pointing to the same object.

String Method
#! /Usr/bin/Python
# Filename: str_methods.py
Name = 'swaroop '# This is a string object
If name. startswith ('swa '):
Print 'Yes, the string starts with "SWA "'
If 'A' in name:
Print 'Yes, it contains the string ""'
If name. Find ('war ')! =-1:
Print 'Yes, it contains the string "war "'
Delimiter = '_*_'
Mylist = ['Brazil ', 'Russia', 'India ', 'China']
Print delimiter. Join (mylist)
Output
$ Python str_methods.py
Yes, the string starts with "SWA"
Yes, it contains the string ""
Yes, it contains the string "war"
Brazil _ * _ Russia _ * _ India _ * _ China

PDB module:

Use PDB for python debugging
Epdb1.py.

# Epdb1.py -- experiment with the python debugger, PDB
A = "AAA"
B = "BBB"
C = "CCC"
Final = A + B + C
Print final
For example, to debug this program:
1: add this sentence before the file to introduce the debugging module.
Import PDB
2: add a line to start debuggingPDB. set_trace ()

File:

 # epdb1.py -- experiment with the Python debugger, pdb
import pdb
a = "aaa"
pdb.set_trace()
b = "bbb"
c = "ccc"
final = a + b + c
print final

You can run this program and it will stop when it is disconnected. It is similar to GDB,
Run the following command:
Press enter to repeat the previous command!
P (print) to view a variable value
N (next) Next
S (STEP) One step to enter the function
C (CONTINUE) move on
L (list) view source code
You can do anything at all at the (PDB) Prompt...

You can also modify the variable value!
For example, to modify the final value, it should be like this! Final = "newvalue"

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.