python 如何读取超大的文件
在 Python 中读取超大的文件(例如,文件的大小大于系统内存)时,通常需要逐行或分块读取,以避免将整个文件加载到内存中,从而导致内存不足的问题。以下是几种常见的方法:
1. 使用 open 和迭代器逐行读取
这是最常见的方法。通过文件对象的迭代器,逐行读取文件。
with open('large_file.txt', 'r', encoding='utf-8') as file:
for line in file:
process_line(line) # 对每行进行处理
这种方式非常高效,因为它不会一次性将整个文件加载到内存,而是逐行读取。
2. 分块读取文件内容
如果需要以更大的块为单位读取,可以使用 read 方法指定块的大小。
with open('large_file.txt', 'r', encoding='utf-8') as file:
while True:
chunk = file.read(1024 * 1024) # 每次读取 1 MB
python requests 模块
requests 是 Python 中一个非常流行的用于发送 HTTP 请求的模块。它提供了一个简单易用的接口,可以用来发送各种类型的 HTTP 请求(如 GET、POST、PUT、DELETE 等),并处理响应数据。以下是 requests 模块的主要功能和常见用法:
安装 requests
如果尚未安装,可以使用以下命令安装:
pip install requests
1. 发送 GET 请求
1. requests.get函数是Python requests库中的一个方法,用于发送HTTP GET请求。其基本语法如下:
response = requests.get(url, params=None, **kwargs)
url:需要发送GET请求的URL地址。
params:可选参数,用于在URL中添加查询字符串参数,参数应以字典形式传递。
**kwargs:其他可选参数,如headers、timeout等,用于控制请求的其他方面。
2. requests.get函数的返回值内容
requests.get函数返回一个Response对象,该对象包含了服务器对请求的响应。Response对象包含以下常用属性和方法:
status_code:HTTP响应状态码(如200表示成功)。
text:响应内容的字符串表示,自动根据响应头中的字符编码进行解码。
content:响应内容的原始字节串,不会自动解码。
json():如果响应内容是JSON格式,该方法会将其解析为Python字典或列表。
headers:一个字典,包含服务器响应的所有头部信息。
python 如何通过subprocess.call调用自定义alias别名
为了更好的通过Python脚本执行linux命令,通过自定义别名(Alias)进行多个命令组合,然而通过python中如何通过subprocess类库
自定义alias
#alias lt='ls --human-readable --size -1 -S --classify'
alias lt='du -sh * | sort -h'
测试调用的Python代码
from subprocess import call
def test():
call("lt")
if __name__ == "__main__":
test()
直接运行上面的代码提示错误信息如下
Traceback (most recent call last):
File "test_alias.py", line 7, in <module>
test()
File "test_alias.py", line 4, in test
call("lt")
File "/Users/shiwei/anaconda3/lib/python3.7/subprocess.py", line 323, in call
with Popen(*popenargs, **kwargs) as p:
File "/Users/shiwei/anaconda3/lib/python3.7/subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "/Users/shiwei/anaconda3/lib/python3.7/subprocess.py", line 1522, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'lt': 'lt'
通过错误信息可以看出lt命令被当作了文件或目录提示找不到
如果您需要的别名是在 ~/.bashrc 中定义的,可以通过尝试以下几种方式进行运行:
1)你必须给’shell’关键字:
subprocess.call('command', shell=True)
否则,您给定的命令用于查找可执行文件,而不是传递给 shell,它是扩展别名和函数等内容的 shell。
from subprocess import call
def test():
call("lt", shell=True)
if __name__ == "__main__":
test()
运行此处代码发现报错找不到文件或目录的错误了,但是出现了新的错误,错误信息如下
# /bin/sh: lt: command not found
有错误信息可以看出还是找不到lt命令,不过不报错误了(此处应该有掌声)
2) 默认情况下,subprocess.call 使用’/bin/sh’ shell。如果这是您要调用的 Bash 别名,则需要使用“可执行”关键字 告诉子进程使用 bash 而不是 sh:
subprocess.call('command', shell=True, executable='/bin/bash')
代码如下
from subprocess import call
def test():
call("lt", shell=True, executable='/bin/bash')
if __name__ == "__main__":
test()
通过执行代码发现,报错的错误同上,还是提示lt找到
3) 但是,/bin/bash 除非作为“交互式”shell(使用“-i”)启动,否则不会获取 ~/.bashrc。不幸的是,您不能传递 executable=’/bin/bash -i’,因为它认为整个值是可执行文件的名称。因此,如果您的别名是在用户的正常交互式启动中定义的,例如在 .bashrc 中,您必须使用以下替代形式调用命令:
subprocess.call(['/bin/bash', '-i', '-c', 命令])
# i.e. shell=False (the default)
from subprocess import call
def test():
call(['/bin/bash', '-i', '-c', 'lt'])
if __name__ == "__main__":
test()
正常执行,成功调用了alias命令
标签: python subprocess alias
python2 python3中long类型的区别
python2 python3中long类型的区别
python2中有long类型
python3中没有long类型,只有int类型
'python' engine because the 'c' engine does not support regex separators
moveielens.py:17: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'.user = pd.read_table(path1, sep='::', header=None, names=unames)
pandas.read_table()函数,读取文件数据时,由于分隔符为'::',弹出如下警告
警告:ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex)
解决方法:增加函数的引擎参数engine='python',如下:
user = pd.read_table(path1, sep='::', header=None, names=unames, engine='python')
标签: python pandas re read_table
RuntimeError: Python is not installed as a framework
今天在mac上,python virtualenv 虚拟环境下运行matplotlib example的时候提示如下报错:python animation/animated_histogram.py
Traceback (most recent call last):
File "animation/animated_histogram.py", line 11, in <module>
import matplotlib.pyplot as plt
File "/Users/shiwei/Documents/python_project/study_matplotlib/lib/python3.5/site-packages/matplotlib/pyplot.py", line 115, in <module>
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
File "/Users/shiwei/Documents/python_project/study_matplotlib/lib/python3.5/site-packages/matplotlib/backends/__init__.py", line 62, in pylab_setup
[backend_name], 0)
File "/Users/shiwei/Documents/python_project/study_matplotlib/lib/python3.5/site-packages/matplotlib/backends/backend_macosx.py", line 17, in <module>
from matplotlib.backends import _macosx
RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information.
标签: python matplotlib RuntimeError
从苦逼到牛逼,详解Linux运维工程师的打怪升级之路
运维工程师是从一个呆逼进化为苦逼再成长为牛逼的过程,前提在于你要能忍能干能拼,还要具有敏锐的嗅觉感知前方潮流变化。如:今年大数据,人工智能比较火……(相对表示就是 Python 比较火)
之前写过运维基础篇,发现对很多人收益挺大,接下来也写下关于这4年多的运维实践经验,从事了2年多游戏运维,1年多安全运维,1年大数据运维,相关行业信息不能算非常精通,但是熟悉和熟练还是相对可以的。
linux运维人员常用工具拓扑详见:
标签: linux rsync sed awk python
Mac pip install protobuf 安装失败
Installing collected packages: six, protobufFound existing installation: six 1.4.1
DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
Uninstalling six-1.4.1:
Exception:
Traceback (most recent call last):
File "/Users/xiaodu/Library/Python/2.7/lib/python/site-packages/pip/basecommand.py", line 215, in main
status = self.run(options, args)
File "/Users/xiaodu/Library/Python/2.7/lib/python/site-packages/pip/commands/install.py", line 342, in run
prefix=options.prefix_path,
File "/Users/xiaodu/Library/Python/2.7/lib/python/site-packages/pip/req/req_set.py", line 778, in install
requirement.uninstall(auto_confirm=True)
解决mac下安装pymssql问题
mac环境:10.11.6
python:2.7.10
sudo pip install pymssql 后出现下面问题:
creating build/temp.macosx-10.11-intel-2.7
error: command 'gcc' failed with exit status 1
错误:error: command 'gcc' failed with exit status 1在 centons 使用pip安装Python模块出现error: command 'gcc' failed with exit status 1 ,明明装了gcc的,怎么会不行呢,然后发觉是failed不是not found,这说明这个错误个gcc没多大关系,应该是缺少某些功能模块,然后谷歌了一下,先后安装了python-devel,libffi-devel后还是不行,最后发觉要安装openssl-devel才行
可如下命令行安装:
yum install gcc libffi-devel python-devel openssl-devel
热门日志
分类
- Django(4)
- ssdb(1)
- Mac(7)
- C(1)
- memcache(1)
- Python(32)
- Vim(8)
- sed(2)
- ansible(3)
- awk(4)
- shell(3)
- about(1)
- git(9)
- bat(4)
- svn(0)
- docker(1)
- Tornado(1)
- go(2)
- 架构(18)
- Vue(1)
- game(2)
- Html(6)
- Java(8)
- Mysql(37)
- Ajax(2)
- Jsp(1)
- Struts(8)
- Linux(72)
- JavaScript(39)
- Staruml(0)
- Mouth(1)
- Php(102)
- Windows(8)
- Message(48)
- Lua(10)
- Compute(1)
- Redis(7)
- Nginx(12)
- Jquery(1)
- Apache(1)
- cocos2d-x(8)