❶ python初学者 今天装上了python,但就是不能正确执行helloworld命令 下面是输入命令后的显示
你可能装的是python 3.他和python2.X有一些区别:
正确的语法应该是print ("helloword")
具体的区别:
1.
如果你下载的是最新版的Python,就会发现所有书中的Hello World例子将不再正确。
Old:
print "Hello World!" #打印字符串
New:
print("Hello World!")
将字符串放到括号中print出来,这种写法对于我这种学习Java出身的人来说,很是亲切啊:)
2.
Old:
guess = int(raw_input('Enter an integer : ')) #读取键盘输入的方法
New:
guess = int(input('Enter an integer : '))
方法名变得更加容易记!
3.
加入了一个新的nonlocal statement,非局部变量,它的范围介于global和local之间,主要用于函数嵌套,用法如下:
#!/usr/bin/python
# Filename: func_nonlocal.py
def func_outer():
x = 2
print('x is', x)
def func_inner():
nonlocal x
x = 5
func_inner()
print('Changed local x to', x)
func_outer()
4.
VarArgs parameters,不知道这个翻译成什么比较妥当?先看例子:
#!/usr/bin/python
# Filename: total.py
def total(initial=5, *numbers, **keywords):
count = initial
for number in numbers:
count += number
for key in keywords:
count += keywords[key]
return count
print(total(10, 1, 2, 3, vegetables=50, fruits=100))
当在参数前面使用*标识的时候,所有的位置参数(1,2,3)作为一个list传递。
当在参数前面使用**标识的时候,所有的关键参数(vegetables=50, fruits=100)作为一个dictionary传递。
5.
关于Packages的话题,暂时没看懂。。。
6.
在数据结构中,多了一种类型:set
Set是一种无序的简单对象的集合,当我们关心一个对象是否在一个集合中存在,而顺序和出现的次数是次要的时候,可以使用set。
7.
关于os.sep方法,(set是separator,分隔符的缩写)
一个很晕菜的例子:
Old:
target_dir = '/mnt/e/backup/'
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
New:
target_dir = 'E:\\Backup'
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
os.sep的功能是自动辨别操作系统,给出不同的分隔符,Windows上是\\,Linux上是/,原理我是明白了,功能也很不错,但是作者的例子。。。。只有一处使用了os.sep,其他的地方还是老的写法啊(E:\\)
8.
可以使用@修饰符声明一个类方法:
@classmethod
def howMany(klass):
'''Prints the current population.'''
print('We have {0:d} robots.'.format(Robot.population))
9.
可以将以个类用Metaclasses的方式声明为抽象类抽象方法
from abc import *
class SchoolMember(metaclass=ABCMeta):
'''Represents any school member.'''
def __init__(self, name, age):
self.name = name
self.age = age
print('(Initialized SchoolMember: {0})'.format(self.name))
@abstractmethod
def tell(self):
'''Tell my details.'''
print('Name:"{0}" Age:"{1}"'.format(self.name, self.age), end=" ")
#pass
10.
文件读写的模式又增加了两种:文本本件('t')二进制文件('b')。
11.将打开文件的操作放到使用with语句修饰的方法中,书上说好处是让我们更专注于文件操作,让代码看起来不凌乱,我一时间还不能体会with的好处,希望大家指点。
#!/usr/bin/python
# Filename: using_with.py
from contextlib import context
@contextmanager
def opened(filename, mode="r")
f = open(filename, mode)
try:
yield f
finally:
f.close()
with opened("poem.txt") as f:
for line in f:
print(line, end='')
12.python3.0中添加了logging mole,给我的感觉类似于Java中的log4j,直接看代码:
import os, platform, logging
if platform.platform().startswith('Windows'):
logging_file = os.path.join(os.getenv('HOMEDRIVE'),
os.getenv('HOMEPATH'), 'test.log')
else:
logging_file = os.path.join(os.getenv('HOME'), 'test.log')
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s : %(levelname)s : %(message)s',
filename = logging_file,
filemode = 'w',
)
logging.debug("Start of the program")
logging.info("Doing something")
logging.warning("Dying now")
❷ python logging 意图:根据运行的不同时间来创建log文件,而不是固定命名,如:2013-06-13.log
原生loggging类+TimedRotatingFileHandler类实现按dayhoursecond切分
importlogging
fromlogging.
log=logging.getLogger(loggerName)
formatter=logging.Formatter('%(name)-12s%(asctime)slevel-%(levelname)-8sthread-%(thread)-8d%(message)s')#每行日志的前缀设置
fileTimeHandler=TimedRotatingFileHandler(BASIC_LOG_PATH+filename,"S",1,10)
fileTimeHandler.suffix="%Y%m%d.log"#设置切分后日志文件名的时间格式默认filename+"."+suffix如果需要更改需要改logging源码
fileTimeHandler.setFormatter(formatter)
logging.basicConfig(level=logging.INFO)
fileTimeHandler.setFormatter(formatter)
log.addHandler(fileTimeHandler)
try:
log.error(msg)
exceptException,e:
print"writeLogerror"
finally:
log.removeHandler(fileTimeHandler)
值 interval的类型
S 秒
M 分钟
H 小时
D 天
W 周
midnight 在午夜
❸ 如何创建 python+requests接口自动化测试框架
需要对于读出来的数据进行相应的处理。 当然示例中只是简单列了一下关于POST,GET等二种方式,实际还有很多其它方式,如put,delete等,请求中也还会包括headers,这些都可以自忆添加上去。
❹ python中,如何添加一个日志点纪录执行到哪个类和方法求大神指点
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s:%(levelname)s:%(message)s',
filename=logging_file,
filemode='w',
)
format 配置如下类似的模版即可
%(pathname)s # 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s # 调用日志输出函数的模块的文件名
%(mole)s # 调用日志输出函数的模块名
%(funcName)s # 调用日志输出函数的函数名
%(lineno)d # 调用日志输出函数的语句所在的代码行
❺ python程序中logging怎么用
简单将日志打印到屏幕:
[python] view plain
import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
输出:
WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message
可见,默认情况下Python的
logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级
CRITICAL > ERROR > WARNING > INFO > DEBUG >
NOTSET),默认的日志格式为日志级别:Logger名称:用户输出消息。
灵活配置日志级别,日志格式,输出位置
[python] view plain
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='/tmp/test.log',
filemode='w')
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
查看输出:
cat /tmp/test.log
Mon, 05 May 2014 16:29:53 test_logging.py[line:9] DEBUG debug message
Mon, 05 May 2014 16:29:53 test_logging.py[line:10] INFO info message
Mon, 05 May 2014 16:29:53 test_logging.py[line:11] WARNING warning message
Mon, 05 May 2014 16:29:53 test_logging.py[line:12] ERROR error message
Mon, 05 May 2014 16:29:53 test_logging.py[line:13] CRITICAL critical message
可见在logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有
filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
format参数中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(mole)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s用户输出的消息
❻ 如何用python检测网站可用性
前言
随着站点的增多,管理复杂性也上来了,俗话说:人多了不好带,我发现站点多了也不好管,因为这些站点里有重要的也有不重要的,重要核心的站点当然就管理的多一些,像一些万年都不出一次问题的,慢慢就被自己都淡忘了,冷不丁那天出个问题,还的手忙脚乱的去紧急处理,所以规范的去管理这些站点是很有必要的,今天我们就做第一步,不管大站小站,先统一把监控做起来,先不说业务情况,最起码那个站点不能访问了,要第一时间报出来,别等着业务方给你反馈,就显得我们不够专业了,那接下来我们看看如果用python实现多网站的可用性监控,脚本如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/env python
import pickle, os, sys, logging
from httplib import HTTPConnection, socket
from smtplib import SMTP
def email_alert(message, status):
fromaddr = '[email protected]'
toaddrs = '[email protected]'
server = SMTP('smtp.163.com:25')
server.starttls()
server.login('xxxxx', 'xxxx')
server.sendmail(fromaddr, toaddrs, 'Subject: %s\r\n%s' % (status, message))
server.quit()
def get_site_status(url):
response = get_response(url)
try:
if getattr(response, 'status') == 200:
return 'up'
except AttributeError:
pass
return 'down'
def get_response(url):
try:
conn = HTTPConnection(url)
conn.request('HEAD', '/')
return conn.getresponse()
except socket.error:
return None
except:
logging.error('Bad URL:', url)
exit(1)
def get_headers(url):
response = get_response(url)
try:
return getattr(response, 'getheaders')()
except AttributeError:
return 'Headers unavailable'
def compare_site_status(prev_results):
def is_status_changed(url):
status = get_site_status(url)
friendly_status = '%s is %s' % (url, status)
print friendly_status
if url in prev_results and prev_results[url] != status:
logging.warning(status)
email_alert(str(get_headers(url)), friendly_status)
prev_results[url] = status
return is_status_changed
def is_internet_reachable():
if get_site_status('www..com') == 'down' and get_site_status('www.sohu.com') == 'down':
return False
return True
def load_old_results(file_path):
pickledata = {}
if os.path.isfile(file_path):
picklefile = open(file_path, 'rb')
pickledata = pickle.load(picklefile)
picklefile.close()
return pickledata
def store_results(file_path, data):
output = open(file_path, 'wb')
pickle.mp(data, output)
output.close()
def main(urls):
logging.basicConfig(level=logging.WARNING, filename='checksites.log',
format='%(asctime)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
pickle_file = 'data.pkl'
pickledata = load_old_results(pickle_file)
print pickledata
if is_internet_reachable():
status_checker = compare_site_status(pickledata)
map(status_checker, urls)
else:
logging.error('Either the world ended or we are not connected to the net.')
store_results(pickle_file, pickledata)
if __name__ == '__main__':
main(sys.argv[1:])
脚本核心点解释:
1、getattr()是python的内置函数,接收一个对象,可以根据对象属性返回对象的值。
2、compare_site_status()函数是返回的是一个内部定义的函数。
3、map() ,需要2个参数,一个是函数,一个是序列,功能就是将序列中的每个元素应用函数方法。
总结
以上就是这篇文章的全部内容,有需要的朋友们可以参考借鉴。
❼ python 怎么将输入目录内的文件拷贝至另一个目录的同名文件夹
这是最近写的一个类似代码,你拿去改改
import shutil
import os
import logging
import sys
logger = logging.getLogger(__name__)
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
def cp_or_mv2(src_file, des_dir, is_):
print(src_file, des_dir)
if os.path.isfile(src_file):
logger.info(f'from file {src_file}')
if is_:
shutil.2(src_file, des_dir)
logger.info(f' to {des_dir}')
else:
des_file = os.path.join(des_dir, src_file)
shutil.move(src_file, des_file)
logger.info(f'move to {des_file}')
else:
logger.info(f'from dir {src_file}')
des_dir_level1 = os.path.join(des_dir, src_file)
shutil.tree(src_file, des_dir_level1, dirs_exist_ok=True)
logger.info(f'to {des_dir_level1}')
if not is_:
shutil.rmtree(src_file)
logger.info(f'deleted {src_file}')
def process_files_in_txt(txt_file, src_dir, des_dir, is_=True):
os.chdir(src_dir)
with open(txt_file, 'r', encoding='utf8', errors='ignore') as f:
for line in f.readlines():
src_file = line.strip()
# logger.info(src_file)
if os.path.exists(src_file):
cp_or_mv2(src_file, des_dir, is_)
else:
logger.warning(f'{src_file} missing!')
if __name__ == '__main__':
process_files_in_txt(r"D:\D\需要拷贝.txt", # 哪些文件(夹)
r"D:\D\Desktop", # 从哪个文件夹
r"D:\D\新建文件夹", # 到哪个文件夹
is_=False) # True复制,False剪切
❽ 初学Python 请教各位前辈,以下这段代码为什么会出错
语法错误。我猜是 yield from 这里错了,但是我没有用过 Python3.5 的 async 和 aiohttp ,所以不清楚具体哪里错了
首先,你用的得是 python3
第二,你这代码哪里抄的,确定有 mole 名字叫 async 吗。。。不应该是 asyncio 吗。。。
‘’
import logging;logging.basicConfig(level=logging.INFO)
import async, os, json, time
from datetime import datetime
from aiohttp import web
def index(request):
return web.Response(body=b'<h1>Awesome</h1>')
@async.coroutine
def init(loop):
app = web.Application(loop=loop)
app.router.add_route('GET', '/', index)
srv = yield from loop.create_server(app.make_handler(),'127.0.0.1',9000)
logging.info('server started at http://127.0.0.1:9000...')
return srv
loop = async.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()
"
运行上面的代码为什么会出现下面的错误?
srv=yield from loop.create_server(app.make_handler(),'127.0.0.1',9000)
^
SyntaxError: invalid syntax