小编chr*_*ley的帖子

python电子邮件错误

我正在尝试通过电子邮件发送结果文件.我收到导入错误:

Traceback (most recent call last):  
  File "email_results.py", line 5, in ?  
    from email import encoders  
ImportError: cannot import name encoders  
Run Code Online (Sandbox Code Playgroud)

我也不确定如何连接到服务器.有人可以帮忙吗?谢谢

#!/home/build/test/Python-2.6.4
import smtplib
import zipfile
import tempfile
from email import encoders
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart

def send_file_zipped(the_file, recipients, sender='myname@myname.com'):
 zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip')
 zip = zipfile.ZipFile(zf, 'w')
 zip.write(the_file)
 zip.close()
 zf.seek(0)

 # Create the message
 themsg = MIMEMultipart()
 themsg['Subject'] = 'File %s' % the_file
 themsg['To'] = ', '.join(recipients)
 themsg['From'] = sender …
Run Code Online (Sandbox Code Playgroud)

python

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

在Python中删除旧目录

我有几个目录,我希望删除超过7天的目录.我已经实现了代码但它似乎没有工作.任何人都可以看到我错在哪里?

def delete_sandbox():

    for directories in os.listdir(os.getcwd()): 

        if not os.path.isdir(directories) or not os.stat(directories).st_ctime < time.time()-(7*24*3600): 
            continue
        os.chdir(directories)
        drop_sandbox()
        os.chdir(rootDir)
        os.system("sudo rm -rf "+directories)
        print 'Folders older than 7 days old dropped and removed'
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助

文件夹沙箱会丢弃,但不会删除.我希望程序进入这些文件夹中的每一个,将沙箱,chnage放回根目录并删除所有旧目录.当我这样做时,文件夹仍然存在.

当我通过文件夹名称中存储的字符串日期删除目录时,此功能也起作用.但是现在我正在尝试获取时间戳,它已停止工作.

我测试过'rm -rf'+directories它并没有删除旧文件夹.当我尝试时,shutil.rmtree我收到错误消息:

Traceback (most recent call last):
  File "yep.py", line 21, in <module>
    delete_sandbox()
  File "yep.py", line 18, in delete_sandbox
    shutil.rmtree(directories)
  File "/home/build/workspace/downloads/Python-2.6.4/Lib/shutil.py", line 208, in rmtree
    onerror(os.listdir, path, sys.exc_info())
  File "/home/build/workspace/downloads/Python-2.6.4/Lib/shutil.py", line 206, in rmtree
    names = os.listdir(path)
OSError: …
Run Code Online (Sandbox Code Playgroud)

python directory time timestamp

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

使用 Unittest Python 进行测试

我正在使用 Python Unittest 运行测试。我正在运行测试,但我想做负面测试,我想测试一个函数是否抛出异常,它通过,但如果没有抛出异常,则测试失败。我的脚本是:

    try:
        result = self.client.service.GetStreamUri(self.stream, self.token)
        self.assertFalse
    except suds.WebFault, e:                        
        self.assertTrue
    else:
        self.assertTrue
Run Code Online (Sandbox Code Playgroud)

即使函数完美运行,这也始终传递为 True。我还尝试了各种其他方式,包括:

    try:
        result = self.client.service.GetStreamUri(self.stream, self.token)
        self.assertFalse
    except suds.WebFault, e:                        
        self.assertTrue
    except Exception, e:
        self.assertTrue
Run Code Online (Sandbox Code Playgroud)

有没有人有什么建议?

谢谢

我试过 assertRaises 没有运气。

    try:
        result = self.client.service.GetStreamUri(self.stream, self.token)
        self.assertRaises(WebFault)
    except suds.WebFault, e:                        
        self.assertFalse
    except Exception, e:                        
        self.assertTrue
Run Code Online (Sandbox Code Playgroud)

它仍然通过。出于某种原因,它不会尝试执行该assertRaises语句。我也试过:(功能应该失败,但测试应该通过)

    try:
        result = self.client.service.GetStreamUri(self.stream, self.token)

    except suds.WebFault, e:                        
        self.assertFalse
    except Exception, e:                        
        self.assertTrue
    else:
        self.assertFalse
Run Code Online (Sandbox Code Playgroud)

出于某种原因,即使函数通过它也不会引发错误。无论异常发生什么,它总是如此。除非有 else 语句,否则它会继续。

找到了一种有效的方法,但它似乎是一种非常糟糕的做事方式:

任何人都可以建议一种更清洁的方法吗?

    try:
        result = self.client.service.GetStreamUri(self.stream, self.token)

    except …
Run Code Online (Sandbox Code Playgroud)

python testing unit-testing exception

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

无法写入文本文件

我正在运行一些测试,需要写入文件.当我运行测试时,open = (file, 'r+')不会写入文件.测试脚本如下:

class GetDetailsIP(TestGet):

    def runTest(self):

        self.category = ['PTZ']

        try:
            # This run's and return's a value
            result = self.client.service.Get(self.category) 

            mylogfile = open("test.txt", "r+")
            print >>mylogfile, result
            result = ("".join(mylogfile.readlines()[2]))
            result = str(result.split(':')[1].lstrip("//").split("/")[0])
            mylogfile.close()
        except suds.WebFault, e:                        
            assert False
        except Exception, e:
            pass
        finally:
            if 'result' in locals():
                self.assertEquals(result, self.camera_ip)
            else:
                assert False
Run Code Online (Sandbox Code Playgroud)

当此测试运行时,没有任何值输入到文本文件中,并且在变量结果中返回一个值.

我也试过了mylogfile.write(result).如果该文件不存在则声明该文件不存在且不创建该文件.

这可能是一个权限问题,其中不允许python创建文件?我确保此文件的所有其他读取都已关闭,因此我不应该锁定该文件.

任何人都可以提出任何建议,为什么会这样?

谢谢

python file-io

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

Python OSError:[Errno 2]没有这样的文件或目录

我正在尝试将此脚本写入我的linux终端,我收到以下错误消息:"OSError:[Errno 2]没有这样的文件或目录".任何人都可以帮忙,谢谢

#!/home/build/test/Python-2.6.4

import os, subprocess

   # Create a long command line
cmd =[\
 "si createsandbox --yes --hostname=be", \
 " --port=70", \
 " --user=gh", \
 " --password=34", \
 "  --populate --project=e:/project.pj", \
 " --lineTerminator=lf new_sandbox"\
 ]

outFile = os.path.join(os.curdir, "output.log")
outptr = file(outFile, "w")

errFile = os.path.join(os.curdir, "error.log")
errptr = file(errFile, "w")

retval = subprocess.call(cmd, 0, None, None, outptr, errptr)

errptr.close()
outptr.close()

if not retval == 0:
  errptr = file(errFile, "r")
  errData = errptr.read()
  errptr.close()
  raise Exception("Error executing command: " …
Run Code Online (Sandbox Code Playgroud)

python

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

类继承

我试图完全掌握Python中的类继承.我用类创建了程序,但它们都在一个文件中.我还创建了包含多个只包含函数的文件的脚本.我已经开始在具有多个文件的脚本中使用类继承,我遇到了问题.我有两个基本脚本,我试图让第二个脚本继承第一个脚本的值.代码如下:

第一个脚本:

class test():

    def q():

        a = 20
        return a

    def w():
        b = 30
        return b

    if __name__ == '__main__':
        a = q()
        b = w()

if __name__ == '__main__':
    (a, b) = test()
Run Code Online (Sandbox Code Playgroud)

第二个脚本:

from class1 import test

class test2(test):

    def e(a, b):
        print a
        print b


    e(a, b)

if __name__ == '__main__':
    test2(test)
Run Code Online (Sandbox Code Playgroud)

任何人都可以向我解释如何让第二个文件继承第一个文件的值?谢谢你的帮助.

python inheritance class

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

如何将函数中的变量传递给类python

我试图将一个变量从一个函数传递给一个类.示例代码如下:

def hello(var):

    return var

class test():
    def __init__(self):
        pass

    def value(self):
        print var

hello(var)
test = test()
test.value()
Run Code Online (Sandbox Code Playgroud)

我想var进入课堂test().

谢谢你的帮助.

python class

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

无法获得variable.replace正常工作

我试图用python文件中的新字符串替换字符串,并将新字符串永久写入它.当我运行下面的脚本时,它会删除部分字符串而不是所有字符串.文件中的字符串是:

self.id = "027FC8EBC2D1"
Run Code Online (Sandbox Code Playgroud)

我必须替换字符串的脚本是:

def edit():

    o = open("test.py","r+") #open 
    for line in open("test.py"):   
        line = line.replace("027FC8EBC2D1","NewValue")  
        o.write(line) 
    o.close()

edit()
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

python

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

在Visual Studio中使用C#输出到DOS

I am using Visual Studio 2010 and I am trying to change the timen on my PC to 11 pm the ``day before yesterday. My question is can somebody tell me what statement that will allow ``me to output directly to DOS using C#.

抱歉写得不好的问题.我试图将时间改为两天前的11:50.我不熟悉Windows中的编程我一直使用Linux.在linux中,我将从命令行执行我的文件并输出到命令行.但是使用Visual Studio我不确定输出到命令行是否会输出到Visual Studio或MS DOS.如果有办法改变timecin,我会很感激.

在命令propt中我输入date 28/07/2010并更改了日期,但是当我进入Console.WriteLine("date 28/07/2010")Visual Studio 2010时,时间保持不变.此语句是否未输出到命令提示符.

谢谢你的帮助

c# visual-studio-2010

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

序列化对象数组以通过套接字发送

我有一个数组,我从数据库ResultSet创建.我正在尝试序列化它,以便我可以通过套接字流发送它.目前我收到一个错误,告诉我该数组不是Serializable.我的代码在下面,第一部分是为数组创建对象的类:

class ProteinData
{
    private int ProteinKey;

    public ProteinData(Integer ProteinKey)
    {
        this.ProteinKey = ProteinKey;
    }

    public Integer getProteinKey() {
        return this.ProteinKey;
    }

    public void setProteinKey(Integer ProteinKey) {
         this.ProteinKey = ProteinKey;
    }
}
Run Code Online (Sandbox Code Playgroud)

填充数组的代码:

public List<ProteinData> readJavaObject(String query, Connection con) throws Exception
    {        
        PreparedStatement stmt = con.prepareStatement(query);
        query_results = stmt.executeQuery();
        while (query_results.next())
        {
            ProteinData pro = new ProteinData();
            pro.setProteinKey(query_results.getInt("ProteinKey"));
            tableData.add(pro);
        }
        query_results.close();
        stmt.close();
        return tableData;
    }
Run Code Online (Sandbox Code Playgroud)

调用它的代码是:

List dataList = (List) this.readJavaObject(query, con);
ObjectOutputStream output_stream = new ObjectOutputStream(socket.getOutputStream());
output_stream.writeObject(dataList);
Run Code Online (Sandbox Code Playgroud)

接收到的代码是:

List …
Run Code Online (Sandbox Code Playgroud)

java sockets arrays serialization object

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