python必备代码_Python常用代码

python使用时间戳命名文件名

import time

filename = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time())) + '.jpg'

更简化的方法:

filename = time.strftime("%Y-%m-%d-%H_%M_%S.jpg")

取得当前脚本所在文件夹下的所有文件

import sys

files = os.listdir(sys.path[0])

使用下面的脚本也可以,但是经常出现异常(可能是因为系统当前目录的影响)

cur_path = os.path.dirname(__file__)

files = os.listdir(cur_path)

敲任意键退出

os.system("pause")

计算代码消耗时间

import os, time

time1 = time.perf_counter()

# do something

time2 = time.perf_counter() - time1

print("用时 {:.3} 秒".format(time2))

os.system("pause")

调用命令行并获取输出

import os

import subprocess,sys

CREATE_NO_WINDOW = 0x08000000 # 隐藏调用的命令行窗口

#r=subprocess.call('dir', creationflags=CREATE_NO_WINDOW, shell=True)

r=subprocess.check_output('dir', creationflags=CREATE_NO_WINDOW, shell=True)

for line in r.splitlines():

print(str(line, encoding='gbk')) # 防止中文乱码

print("处理完毕")

os.system("pause")

在屏幕同一位置输出信息(不换行)

import time

i = 0

for i in range(20):

time.sleep(1)

print("\r# Process: %0.1f %%" % (float(i + 1) / float(20) * 100), end="")

“\r” 表示回车(光标回到行首),需要配合 end="" 使用,才能每次在同一行输出信息。

使用 requests 访问 https 网站

import urllib3

# 使用requests访问https站点时,设置verify=False后,禁止显示警告信息

urllib3.disable_warnings()

session = requests.Session()

response = session.get(url, headers = headers, verify=False, timeout=3)

取得并显示验证码图片

response = session.get("https://pan.baidu.com/DrawServlet?Rand={}".format(random.random() * 10000), headers = headers, verify=False, timeout=3)

image = Image.open(BytesIO(response.content))

image.show()

确保输入的是整数

a = 0

while a == 0:

try:

a = int(input("请输入刷新时长(单位:秒):"))

except:

pass

print(a)

使用 requests 提交数据

#coding=utf-8

import requests

import time

myheader = '''

Accept:*/*

Accept-Language:zh-cn

x-requested-with:XMLHttpRequest

Content-Type:application/json

Accept-Encoding:gzip, deflate

User-Agent:Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)

Host:xjxt.lndisedu.com

Connection:Keep-Alive

Cache-Control:no-cache

'''

session = requests.session()

Token = Login(session)

try:

if Token:

headers = MakeHeader(myheader)

headers['ccrf-token'] = Token

url = 'http://map.baidu.com/test.jsp?token={}'.format(Token)

params = '{"params":{"javaClass":"ParameterSet","map":{"XS_JBXX_ID":"","SFSQZNM":"","SFSQZNM_JCWG":"0"},"length":3}}'

params = params.replace("", Id)

params = params.replace("", str(flag))

i = 0

# 尝试提交 3 次

while i < 3:

try:

# 不指定 timeout 参数,转接超时程序会直接失去反应

r = session.post(url, data=params, headers=headers, timeout=5)

if r.text != '{"map":{},"javaClass":"ParameterSet"}':

print('ID:{} SuiQian Error'.format(Id))

else:

return

except requests.exceptions.RequestException:

i += 1

finally:

Logout(session)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值