我最近迁移到了Py 3.5.这段代码在Python 2.7中正常工作:
with open(fname, 'rb') as f:
lines = [x.strip() for x in f.readlines()]
for line in lines:
tmp = line.strip().lower()
if 'some-pattern' in tmp: continue
# ... code
Run Code Online (Sandbox Code Playgroud)
升级到3.5后,我得到了:
TypeError: a bytes-like object is required, not 'str'
Run Code Online (Sandbox Code Playgroud)
最后一行的错误(模式搜索代码).
我已尝试.decode()在语句的任何一侧使用该函数,也尝试过:
if tmp.find('some-pattern') != -1: continue
Run Code Online (Sandbox Code Playgroud)
- 无济于事.
我能够迅速解决几乎所有2:3的问题,但这个小小的陈述让我烦恼.
如何使用subprocess.call()?获取进程的输出?
传递StringIO.StringIO对象stdout会出现此错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call
return Popen(*popenargs, **kwargs).wait()
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 588, in __init__
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 945, in _get_handles
c2pwrite = stdout.fileno()
AttributeError: StringIO instance has no attribute 'fileno'
>>>
Run Code Online (Sandbox Code Playgroud) 在Flickr API文档中,您需要找到字符串的MD5总和以生成[api_sig]值.
如何从字符串生成MD5总和?
Flickr的例子:
串: 000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite
MD5总和: a02506b31c1cd46c2e0b6380fb94eb3d
我使用了hashlib(它取代了Python 2.6/3.0中的md5),如果我打开一个文件并将其内容放入hashlib.md5()函数中,它工作正常.
问题在于非常大的文件,它们的大小可能超过RAM大小.
如何在不将整个文件加载到内存的情况下获取文件的MD5哈希值?
我正在使用一个返回字节字符串的库,我需要将其转换为字符串.
虽然我不确定区别是什么 - 如果有的话.
我正在尝试为命令行程序(svnadmin verify)编写一个包装器脚本,它将为操作显示一个很好的进度指示器.这要求我能够在输出后立即查看包装程序的每一行输出.
我想我只是执行程序使用subprocess.Popen,使用stdout=PIPE,然后读取每一行,并相应地对其进行操作.但是,当我运行以下代码时,输出似乎在某处缓冲,导致它出现在两个块中,第1行到第332行,然后是333到439(输出的最后一行)
from subprocess import Popen, PIPE, STDOUT
p = Popen('svnadmin verify /var/svn/repos/config', stdout = PIPE,
stderr = STDOUT, shell = True)
for line in p.stdout:
print line.replace('\n', '')
Run Code Online (Sandbox Code Playgroud)
稍微查看子进程的文档后,我发现bufsize参数为Popen,所以我尝试将bufsize设置为1(缓冲每行)和0(无缓冲区),但这两个值似乎都没有改变行的传递方式.
此时我开始掌握吸管,所以我编写了以下输出循环:
while True:
try:
print p.stdout.next().replace('\n', '')
except StopIteration:
break
Run Code Online (Sandbox Code Playgroud)
但得到了相同的结果.
是否有可能获得使用子进程执行的程序的"实时"程序输出?Python中是否有其他选项可以向前兼容(不是exec*)?
我设法让我的第一个python脚本工作,从URL下载.ZIP文件列表,然后继续提取ZIP文件并将它们写入磁盘.
我现在无法实现下一步.
我的主要目标是下载并解压缩zip文件,并通过TCP流传递内容(CSV数据).如果我能逃脱它,我宁愿不将任何zip或解压缩的文件写入磁盘.
这是我当前的脚本,但不幸的是必须将文件写入磁盘.
import urllib, urllister
import zipfile
import urllib2
import os
import time
import pickle
# check for extraction directories existence
if not os.path.isdir('downloaded'):
os.makedirs('downloaded')
if not os.path.isdir('extracted'):
os.makedirs('extracted')
# open logfile for downloaded data and save to local variable
if os.path.isfile('downloaded.pickle'):
downloadedLog = pickle.load(open('downloaded.pickle'))
else:
downloadedLog = {'key':'value'}
# remove entries older than 5 days (to maintain speed)
# path of zip files
zipFileURL = "http://www.thewebserver.com/that/contains/a/directory/of/zip/files"
# retrieve list of URLs from the webservers
usock = urllib.urlopen(zipFileURL) …Run Code Online (Sandbox Code Playgroud) 我正在使用Python在Python中生成XML文档ElementTree,但该tostring函数在转换为纯文本时不包含XML声明.
from xml.etree.ElementTree import Element, tostring
document = Element('outer')
node = SubElement(document, 'inner')
node.NewValue = 1
print tostring(document) # Outputs "<outer><inner /></outer>"
Run Code Online (Sandbox Code Playgroud)
我需要我的字符串包含以下XML声明:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
Run Code Online (Sandbox Code Playgroud)
但是,似乎没有任何记录的方法可以做到这一点.
是否有适当的方法来呈现XML声明ElementTree?
我有两个脚本,Server.py和Client.py.我有两个目标:
这是我的Server.py:
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.3"
port = 8000
print (host)
print (port)
serversocket.bind((host, port))
serversocket.listen(5)
print ('server started and listening')
while 1:
(clientsocket, address) = serversocket.accept()
print ("connection found!")
data = clientsocket.recv(1024).decode()
print (data)
r='REceieve'
clientsocket.send(r.encode())
Run Code Online (Sandbox Code Playgroud)
这是我的客户:
#! /usr/bin/python3
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host ="192.168.1.3"
port =8000
s.connect((host,port))
def ts(str):
s.send('e'.encode())
data = ''
data = s.recv(1024).decode()
print (data)
while 2:
r = input('enter')
ts(s)
s.close ()
Run Code Online (Sandbox Code Playgroud)
该功能第一次工作('e'进入服务器,我收到返回消息),但如何让它一次又一次地发生(像聊天应用程序)?问题在第一次之后开始.消息不会在第一次之后发送.我究竟做错了什么?我是python的新手,所以请稍微详细一点,如果可以,请提供整个内容的源代码.
在Windows 10上安装了TensorFlow r0.12(CPU)的测试时,我发现打印的字符串最后总是带有'b'.python的打印是正常的.我无法弄清楚是什么原因来到这里寻求帮助.代码如下:
>>>import tensorflow as tf
>>>hello = tf.constant('Hello, TensorFlow!')
>>>sess = tf.Session()
>>>print(sess.run(hello))
b'Hello, TensorFlow!'
Run Code Online (Sandbox Code Playgroud) python ×10
byte ×2
md5 ×2
string ×2
subprocess ×2
character ×1
elementtree ×1
file ×1
flickr ×1
hashlib ×1
networking ×1
pipe ×1
python-3.x ×1
sockets ×1
stringio ×1
tensorflow ×1
unzip ×1
windows ×1
xml ×1