Exception handling, module package, Time module, subprocess (Invoke shell command)

Source: Internet
Author: User
Tags timedelta

Exception handling

You can use the Try/except statement to catch an exception.
The try/except statement is used to detect errors in a try statement block, allowing the except statement to catch exception information and handle it.
If you do not want to end your program when an exception occurs, simply capture it in a try.

More exception Keywords:
Http://www.runoob.com/python/python-exceptions.html

Exception: base class for general errors
IOError: Input/output operation failed
Example 1: Write a message to the Tt.txt file, and if an error is given, it will print incorrectly

try:    with open(‘tt.txt‘) as fd:        fd.write(‘123\n456‘)except IOError as t:    print(‘Error:该文件不存在‘)else:    print(‘写入成功‘)

Example 2:
Returns from a JSON object

import jsondef test():    result = dict()    try:        print(2/0)    except Exception as a:        result["msg"] = "除数不能为0"        result["code"] = 403        result["data"] = [{"a": 1}, {"b": 2}]    finally:        print(type(json.dumps(result)))        json_str=json.dumps(result,ensure_ascii=False)        return json_strif __name__ == ‘__main__‘:    print(test())
Import of Module Packages

From Directory name Import function name

Call:
function name. Functions (Methods)

To create a new module package:
1. Create a new Product_oss project directory

2. Create a new module package for Test1, which has an extra init. py Empty File

3. Create a new main.py in the Test1 directory

def add_num (x, y):
return x + y

If name = = 'main':
Add_num (ON)

4. Create a new test.py under the Product_oss directory

5. The directory structure is as follows:

6, in the test.py to import the main.py method

From test1 import main as TT

Print (Tt.add_num (10,10))

Time Module

1. Import Module
From datetime import datetime, Timedelta
2. Print (DateTime.Now ())
2018-04-28 12:14:21.867118 #年-month-day hour: minute: sec: ms

3. Display year-month-day, hour, minute, second, millisecond
Print (DateTime.Now (). Year)
Print (DateTime.Now (). Month)
Print (DateTime.Now (). Day)
Print (DateTime.Now (). Hour)
Print (DateTime.Now (). minute)
Print (DateTime.Now (). Second)
Print (DateTime.Now (). microsecond)

4, Display month day-hour-minute-second
Print (DateTime.Now (). Strftime ("%y-%m-%d_%h:%m:%s"))
2018-04-28_12:17:03

5, after 3 hours
In []: Nowtime = DateTime.Now ()

in [+]: Nowtime + = Timedelta (hours=+3)

in [+]: print (nowtime)
2018-04-28 17:33:19.152888

Time Module
in [+]: Import time

Timestamp: Number of seconds starting from 1970-01-01 to now
in [+]: print (Time.time ())
1524897275.16

in [+]: print (Time.ctime ())
Sat APR 28 14:35:14 2018

Commands for calling Linux systems
Standard output to piping (pipe)

From subprocess Import Popen,pipe

In [Subprocess.call]: (' ls/root ', shell=true)
123.txt anaconda-ks.cfg python shell test venv
OUT[52]: 0

in [+]: pp=popen ([' ls ', '/root '],stdout=pipe)
In []: Tt=pp.stdout.read (). Strip ()
in [+]: TT
OUT[49]: ' 123.txt\nanaconda-ks.cfg\npython\nshell\ntest\nvenv '

Exception handling, module package, Time module, subprocess (Invoke shell command)

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.