小编use*_*314的帖子

如何测试写入文件的Python函数

我有一个Python函数,它将列表作为参数并将其写入文件:

def write_file(a):
    try:
        f = open('testfile', 'w')
        for i in a:
            f.write(str(i))

    finally:
        f.close()
Run Code Online (Sandbox Code Playgroud)

我该如何测试这个功能?

def test_write_file(self):
    a = [1,2,3]
    #what next ?
Run Code Online (Sandbox Code Playgroud)

python unit-testing

4
推荐指数
1
解决办法
204
查看次数

写入文件 f 后,调用 f.read() 返回 None

问题是写入文件后它是空的,我不明白为什么。这是我的代码:

    self.f = tempfile.NamedTemporaryFile(delete=False)    
    for i in range(self.num_chars_file):
        self.f.write(str(i))
    reader_writer.testfile = self.f.name
    print '************************'
    print self.f.read()
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况,以及如何纠正这种情况?

python unit-testing temporary-files

2
推荐指数
1
解决办法
537
查看次数

Python使用主机名,主机名使用IP

在python中我需要从主机名获取IP:

socket.gethostbyname('www.python.org') # returns ip good
socket.gethostbyname('http://python.org') # raises error
Run Code Online (Sandbox Code Playgroud)

我需要处理以"http://"开头的主机名,所以我想出了一种方法来重新制作它们:

a = 'http://python.org'
a.replace('http://', 'www.')
print a # Why does it print http://python.org ???
Run Code Online (Sandbox Code Playgroud)

我不确定我做对了.Plz帮助我将这种类型的主机名转换为IP

python sockets string

0
推荐指数
1
解决办法
323
查看次数

正则表达式,找到<a>标签中的所有"href"

我有一个正则表达式,在标签中搜索"href"属性,但它目前效果不佳:

<a[^>]* href="([^"]*)"
Run Code Online (Sandbox Code Playgroud)

它从中发现:

<a href="http://something" title="Development of the Python language and website">Core Development</a>
Run Code Online (Sandbox Code Playgroud)

这一行:

<a href="http://something"
Run Code Online (Sandbox Code Playgroud)

但我只需要找到:

http://something
Run Code Online (Sandbox Code Playgroud)

python regex

-3
推荐指数
1
解决办法
3975
查看次数

标签 统计

python ×4

unit-testing ×2

regex ×1

sockets ×1

string ×1

temporary-files ×1