help帮助系统,一个好的方法是直接看自带的帮助,尽量不用baidu
help()是进入交互式帮助界面
quit是退出交互式帮助界面 [root@kvm1 python]# python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help
Type help() for interactive help, or help(object) for help about object.
>>> help() Welcome to Python 2.7! This is the online help utility. If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/2.7/tutorial/. Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam". help> help> quit You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt. 下面是模块,关键字,主题的列表
help> modules Please wait a moment while I gather a list of all available modules... ANSI base64 io sched
BaseHTTPServer bdb itertools screen
Bastion binascii javapackages select
CDROM binhex json selinux
CGIHTTPServer bisect jsonschema semanage
Enter any module name to get more help. Or, type "modules spam" to search
for modules whose descriptions contain the word "spam". help> keywords Here is a list of the Python keywords. Enter any keyword to get more help. and elif if print
as else import raise
assert except in return
help> topics Here is a list of available topics. Enter any topic name to get more help. ASSERTION DEBUGGING LITERALS SEQUENCEMETHODS2
ASSIGNMENT DELETION LOOPING SEQUENCES
ATTRIBUTEMETHODS DICTIONARIES MAPPINGMETHODS SHIFTING
ATTRIBUTES DICTIONARYLITERALS MAPPINGS SLICINGS
导入一个自定义模块
[root@250-shiyan ~]# mkdir python
[root@250-shiyan ~]# cd python/
[root@250-shiyan python]# cat >hello.py
#! /usr/bin/env python
print "hello world"
[root@250-shiyan python]# python hello.py
hello world
[root@250-shiyan python]# ll
total 4
-rw-r--r-- 1 root root 43 Jul 16 12:50 hello.py
[root@250-shiyan python]# chmod 755 hello.py
[root@250-shiyan python]# ./hello.py
hello world
[root@250-shiyan python]# python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello
hello world
>>> quit()
[root@250-shiyan python]# ll
total 8
-rwxr-xr-x 1 root root 43 Jul 16 12:50 hello.py
-rw-r--r-- 1 root root 116 Jul 16 12:51 hello.pyc
需求逐渐增加
1.去掉用户名前后的空格 strip()
2.判断用户名不为空
不输入或输入空格都是空 用len()
3.判断用户名是否输错 !=
4.超过3次就退出
需要一个计数器来判断次数
程序是一步步做出来的,这次加一点,下次加一点。
1.第一次只是基本的格式化输出 print "your name is %s" %name
2.第二次加入 strip()方法去掉前后的空格,保证程序的健壮性,来防止用户输入错误。
3.第三次加入while循环,使得用户只能输入正确的aa,才能返回正常,否则不输入或输入错误都不行
[root@kvm1 python]# cat input2.py
#! /usr/bin/env python #name= raw_input("please enter your name: ").strip()
while True:
name= raw_input("please enter your name: ").strip()
if len(name)==0:
print "Empty name,try again:"
continue
elif name != "aa"
print "Error name,try again: %s " %name
continue
break
age=int(raw_input("please enter your age: "))
sex= raw_input("your sex is: ")
dep= raw_input("which department: ")
#message = '''Information of the company staff:
# Name:%s
# Age:%d
# Sex:%s
# Dep:%s
# ''' % (name,age,sex,dep)
#print message if name != "aa":
print "you are not in user list"
else:
print "welcome you are login"
制作tab补全
centos7是下面这个目录,ubuntu可能不一样
[root@kvm1 site-packages]# pwd
/usr/lib/python2.7/site-packages
[root@kvm1 site-packages]# vi tab.py
#!/usr/bin/env python
# python startup file
import sys
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter [root@kvm1 site-packages]# python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import tab
>>> sys.
sys.__class__( sys.__subclasshook__( sys.exitfunc( sys.path_importer_cache
[root@kvm1 site-packages]# ll tab.py
tab.py tab.pyc
进入python,import tab一下,就有了tab.pyc这个模块了
>>> import os shutil
>>> os.getcwd()
'/root/code/python'
>>> os.listdir("/home")
['zf', 'img', 'iso', 'docker']
>>> os.path.isfile("/tmp")
False
>>> os.path.isfile("input.py")
True
>>> os.path.isabs("input.py")
False
>>> os.path.isabs("/root/code/python/input.py")
True
>>> os.path.split("/root/code")
('/root', 'code')
>>> os.system("free")
total used free shared buff/cache available
Mem: 32657352 16457992 6302376 229644 9896984 15655708
Swap: 14352380 0 14352380
0
>>> os.linesep
'\n'
>>> os.name
'posix' >>> import tab
>>> from os import system
>>> system("df -h")
python 将用户输入录入到sqlite3数据库中,不过这个脚本有点问题,自动创建库,因为首次要建表,第二次录入时会报错,所以应该加一个判断表是否存在的语句块,然后再插入数据,查询数据时,有几行查几行,也可以一次查完(根据代码适度调整吧)
[root@kvm1 python]# cat input3.py
#! /usr/bin/env python import sqlite3 name= raw_input("please enter your name: ")
age=int(raw_input("please enter your age: "))
sex= raw_input("your sex is: ")
dep= raw_input("which department: ") # test.db is a file in the working directory.
conn = sqlite3.connect("test.db")
c = conn.cursor()
# create tables
c.execute('''CREATE TABLE staff
(name string,
age int,
sex string,
dep string)''')
# save the changes
conn.commit() #staffs = [("a",10,"male","caiwu"),
# ("b",15,"female","hr"),
# ("c",20,"male","it")] # execute "INSERT"
#c.execute("INSERT INTO staff VALUES (,age,sex,dep)")
# using the placeholder
c.execute("INSERT INTO staff VALUES (?, ?, ?, ?)", (name,age,sex,dep)) #c.execute('UPDATE staff SET price=? WHERE id=?',(1000, 1))
#c.execute('DELETE FROM staff WHERE id=2')
#c.execute('DROP TABLE staff')
# execute multiple commands
#c.executemany('INSERT INTO staff VALUES (?, ?, ?, ?)', staffs)
conn.commit()
#SQL语句中的参数,使用"?"作为替代符号,并在后面的参数中给出具体值。这里不能用Python的格式化字符串,如"%s",因为这一用法容易受到SQL注入攻击。 c.execute('SELECT * FROM staff')
print(c.fetchone())
print(c.fetchone()) # retrieve all records as a list
#c.execute('SELECT * FROM staff')
#print(c.fetchall()) # iterate through the records
#for row in c.execute('SELECT name, price FROM book ORDER BY sort'):
# print(row) # close the connection with the database
conn.close()
全局替换,注意print aa,这个逗号,不加的话,最后修改后的list.txt格式不正确
[root@kvm1 python]# python rep.py
[root@kvm1 python]# cat list.txt
1 zhou aa-1 15897638976
2 wu feaa 18946578291
3 zheng aa-1 02134578129
4 wang feaa 01098452345
5 feng feaa 02987654890
6 cheng feaa 15771543637
7 chu aa-1 18691234578
8 wei aa-1 18097643789
9 li aa-1 17654893092 [root@kvm1 python]# cat rep.py
#! /usr/bin/env python import fileinput
for line in fileinput.input("list.txt",inplace=1):
aa=line.replace("male","aa")
print aa,
将字符串转成列表
>>> name
['alex', 'fog', 4, 'wo', 'wo']
>>> name.count('wo')
2
>>> 'fog' in name
True
>>> 'fog1' in name
False 将字符串转成列表,默认是以空格为分隔符的,也可以以某个符号为分隔符例如=
>>> a='wowiewoewie'
>>> a.split()
['wowiewoewie']
>>> a='w o w i ew o ew ie'
>>> a.split()
['w', 'o', 'w', 'i', 'ew', 'o', 'ew', 'ie']
>>> a='w o = w i ew = o ew ie'
>>> a.split('=')
['w o ', ' w i ew ', ' o ew ie']
>>> b=a.split('=')
>>> b
['w o ', ' w i ew ', ' o ew ie']
一个购物车程序,用到了列表
[root@kvm1 python]# cat shop.py
#! /usr/bin/env python import sys
products=['car','phone','food','colths','bicyle']
prices=[5000,2010,202,120,549]
shop=[]
while True:
try:
salary=int(raw_input("please input your money "))
break
except ValueError:
print "please input a number,not string."
while True:
print "the have to the shop,please choose one to buy"
for p in products:
print "%s,%s" %(p,prices[products.index(p)])
choice=raw_input("please input one item to buy: ")
F_choice=choice.strip()
if F_choice =='quit':
print "you have bought these things: %s" % shop
sys.exit()
if F_choice in products:
product_price_index=products.index(F_choice)
product_price=prices[product_price_index]
print "%s $%s" %(F_choice,product_price)
if salary > product_price:
shop.append(F_choice)
print "added %s into your shop list" %F_choice
salary =salary - product_price
print "salary is left: $",salary
else:
if salary < min(prices):
print "rest of money cant buy anything"
print "you have these things: %s" % shop
sys.exit()
else:
print "sorry,you cant affor this thing"
从文件中读入数据,并将其转为列表
将文本文件转成列表
[root@kvm1 python]# cat aa.txt
car 1000
phone 500
colth 231
coffe 59
bicyle 400
[root@kvm1 python]# cat b.py
#! /usr/bin/env python products = []
prices = [] f = file("aa.txt")
for line in f.readlines():
p = line.split()[0]
pri = int(line.split()[1])
products.append(p)
prices.append(pri)
print products
print prices [root@kvm1 python]# python b.py
['car', 'phone', 'colth', 'coffe', 'bicyle']
[1000, 500, 231, 59, 400]
将列表导出到一个文件中
[root@kvm1 python]# cat pat.py
import sys
f=open('pat.txt','w') for i in sys.path:
f.write(i+'\n') f.close()
[root@kvm1 python]# python pat.py
[root@kvm1 python]# cat pat.txt
/root/code/python
/usr/lib/python2.7/site-packages/mechanize-0.2.5-py2.7.egg
/usr/lib64/python27.zip
/usr/lib64/python2.7
/usr/lib64/python2.7/plat-linux2
/usr/lib64/python2.7/lib-tk
/usr/lib64/python2.7/lib-old
/usr/lib64/python2.7/lib-dynload
/usr/lib64/python2.7/site-packages
/usr/lib64/python2.7/site-packages/gtk-2.0
/usr/lib/python2.7/site-packages sys.path这个是模块的搜索路径,如果都没有,就报错。
所以可以将自己的.py文件放入以下任何一个目录中,就可随便导入了,并生成pyc文件