❶ 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