小编shx*_*hx2的帖子

ipython调试器:交互式pdb上的完全回溯?

我最近从ipython0.10切换到ipython0.11.在ipython0.11中,我只看到python调试器参与(即使用%pdb)时的完整回溯的一小段,而在ipython0.10中我会看到完整的回溯.据我所知,pdb命令行无法直接访问完整的回溯 - 您可以使用'u'浏览它,但无法直接看到它.

那么,有没有办法显示完整的追溯?比如配置参数?

或者,更有用的是,有没有办法让ipython只显示被捕获的异常,而不是显示它被捕获的代码中的位置?

编辑:示例:

In [1]: pdb
Automatic pdb calling has been turned ON

In [2]: 1/0
> <ipython-input-2-05c9758a9c21>(1)<module>()
     -1 1/0

ipdb> q
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
/Users/adam/<ipython-input-2-05c9758a9c21> in <module>()
----> 1 1/0

ZeroDivisionError: integer division or modulo by zero
Run Code Online (Sandbox Code Playgroud)

我想 q退出pdb 之前看到ZeroDivisionError .

python ipython pdb ipdb

6
推荐指数
1
解决办法
5584
查看次数

将unicode对象与字符串对象进行比较时出现奇怪的行为

当比较python中的两个字符串时,它工作正常,当比较一个string对象与一个unicode对象时,它会按预期失败,但是当比较一个string对象与转换后的unicode (unicode --> str)对象时,它会失败

演示:

按预期工作:

>>> if 's' is 's': print "Hurrah!"
... 
Hurrah!
Run Code Online (Sandbox Code Playgroud)

差不多是啊:

>>> if 's' is u's': print "Hurrah!"
... 
Run Code Online (Sandbox Code Playgroud)

没想到:

>>> if 's' is str(u's'): print "Hurrah!"
... 
Run Code Online (Sandbox Code Playgroud)

当两个类型属于同一类时,为什么第三个示例不能按预期工作?

>>> type('s')
<type 'str'>

>>> type(str(u's'))
<type 'str'>
Run Code Online (Sandbox Code Playgroud)

python unicode python-2.7

6
推荐指数
1
解决办法
435
查看次数

函数不会返回'for'循环的所有结果

我已经做了一个简单的功能,根据您决定运行的数字打印出时间表图表.由于我对该语言的基本理解,我遇到的问题是为什么它只返回第一个循环而没有别的.

def timestables(number):
  for a in range(1, number+1):
    b = a*a
    c = a
    return (str(c) + " * " + str(c) + " = " + str(b))

print(timestables(5))
Run Code Online (Sandbox Code Playgroud)

我得到答案..

1 * 1 = 1
Run Code Online (Sandbox Code Playgroud)

我试图通过使用print而不是return来纠正这个问题,但这最终会导致出现None.

def timestables(number):
  for a in range(1, number+1):
    b = a*a
    c = a
    print (str(c) + " * " + str(c) + " = " + str(b))

print(timestables(5))
Run Code Online (Sandbox Code Playgroud)

我得到答案..

1 * 1 = 1
2 * 2 = 4
3 * 3 = 9 …
Run Code Online (Sandbox Code Playgroud)

python for-loop

5
推荐指数
2
解决办法
3215
查看次数

使用 paramiko 的 sftp 时出现“No such file”错误

我想使用 python 将文件本地传输到服务器

#!/usr/bin/env python

import os

import paramiko

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(hostname, username="username", password="password")

ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('ls /tmp')

print "output", ssh_stdout.read() 

#Reading output of the executed command

error = ssh_stderr.read()

#Reading the error stream of the executed command

print "err", error, len(error)

#Transfering files to and from the remote machine

sftp = ssh.open_sftp()

#sftp.get("/home/developers/screenshots/ss.txt", "/home/e100075/python/ss.txt")

sftp.put('/home/e100075/python/ss.txt', '/home/developers/screenshots/ss.txt')

sftp.close()

ssh.close()
Run Code Online (Sandbox Code Playgroud)

运行后出现以下错误

File "file_copy.py", line 21, in <module>

    sftp.put('/home/e100075/python/ss.txt', '/home/developers/screenshots/ss.txt')

  File "/usr/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 565, in put

    fr = …
Run Code Online (Sandbox Code Playgroud)

python linux ssh paramiko python-2.7

5
推荐指数
1
解决办法
8252
查看次数

在python中指定日期时间所在的时区

我有一个从数据库中获取的日期时间,这个日期时间是一个 UTC 日期时间。但是当我从数据库中提取它时,它不知道时区。我需要做的是将此日期时间转换为另一个函数的“纪元秒数”时间。问题在于,系统的时间在 PST 中,由于特定原因我无法更改它。

所以,我想要做的是,获取我从数据库中获得的这个日期时间,并告诉 python 这个日期时间是一个 UTC 日期时间。我所做的每一种方式都会导致它因时区转换而失去时间或获得时间。同样,不是试图转换时间,只是试图指定它是 UTC。

如果有人可以帮助解决这个问题,那就太好了。

谢谢!

例子

假设 database_function() 返回的日期时间数据类型为 '2013-06-01 01:06:18'

datetime = database_function()
epoch = datetime.strftime('%s')

pytz.utc.localize(database_function()).datetime.strftime('%s')
datetime.replace(tzinfo=pytz.utc).datetime.strftime('%s')
Run Code Online (Sandbox Code Playgroud)

这两个都返回 1370077578 的纪元时间戳但是,它应该返回每个http://www.epochconverter.com/的时间戳 1370048778 记住,这个时间戳是一个 UTC 时间戳

python timezone datetime

5
推荐指数
1
解决办法
9942
查看次数

Pymongo散装插入不起作用

我正在按照教程http://api.mongodb.org/python/current/tutorial.html进行批量插入.但是,我收到了下面列出的错误.我错过了什么?reviews_array是一个json_array

client = MongoClient()
client = MongoClient('localhost', 27017)
db = client.is_proj

db_handle = db.reviews


self.db_handle.insert_many(reviews_array)
Run Code Online (Sandbox Code Playgroud)

错误:

TypeError: 'Collection' object is not callable. If you meant to call the 'insert_many' method on a 'Collection' object it is failing because no such method exists.
Run Code Online (Sandbox Code Playgroud)

collections bulkinsert mongodb pymongo mongodb-query

5
推荐指数
1
解决办法
3284
查看次数

使用 Klepto 保存和编辑 Python

好的,所以我的问题非常具体,我提前道歉。我是一名新程序员,并尝试从头开始自己开发。这是相对成功的,只有我有最后一个问题,我可以看到。您可以在此处完整查看我的代码。

项目

所以我遇到的问题与我保存文件的方式有关。我首先尝试腌制它,因为它是一本字典,但我一直收到错误,因为我的字典是
(name, class) 对。

我在这里搜索,发现我可以尝试使用 JSON 来做同样的事情。以同样的错误结束。最终我找到了有效的 klepto 模块。我成功保存了我的字典并成功加载了它。直到后来我才发现我可以向文件添加新项目,但是每当我从字典中删除某些内容并保存时。下次我加载它。我取下的钥匙还在。

TLDR:可以将内容添加到我的 dict 中并保存到 txt 文件,但是当我从 dict 中删除并保存时,它不会保存已删除的密钥。

无论如何,我很难确定我的问题出在我保存文件的方式或加载文件的方式上,还是两者兼而有之?任何帮助将不胜感激。

编辑:好的,我假设这是我当前设置的保存和加载方式。

try:
    alcohols = file_archive('Alcohols.txt')
    alcohols.load()
except IOError:
    alcohols = {}
    print('alcohols doesn\'t exist.')
Run Code Online (Sandbox Code Playgroud)

print('Exiting and saving the data.')
        alcohols.dump('Alcohols.txt') #saves the dictionary data as is
Run Code Online (Sandbox Code Playgroud)

它在添加新项目时可以很好地保存字典,但说我必须进行编辑并删除某些内容然后保存并退出。下次加载时,它将包含旧项目以及任何新项目。奇怪的是,我似乎在我的所有编辑中都破坏了一些东西。不保存新条目。

编辑2:

                del alcohols[name] #deletes the key out of the dict
Run Code Online (Sandbox Code Playgroud)

这就是我删除密钥的方式。最初我使用的是 pop 方法,但是当它无法保存更改时,我尝试了此方法。请注意,它确实从字典中删除了它们的键、值,但保存和重新加载不会反映这种变化。

                alcohols[name] = Alcohol() #instantiates the new class
Run Code Online (Sandbox Code Playgroud)

这就是我创建新键值对的方式。

已解决编辑:

我的问题是我从字典中删除它们的方式。以防万一有人后来偶然发现这里。看看@Mike Mckerns 的回答。不得不从存档的字典中删除。

python dictionary pickle klepto

5
推荐指数
1
解决办法
4371
查看次数

Python3:作为Cronjob运行时的configparser KeyError

我有一个简单的python3脚本,当我从控制台运行它时,它可以工作:

import configparser

file = 'config_test.ini'
config = configparser.ConfigParser()
config.read(file)
for key in config['test_section']: print(key)
Run Code Online (Sandbox Code Playgroud)

被调用的ini文件看起来像这样:

[test_section]
testkey1 = 5
testkey2 = 42878180
testkey3 = WR50MS10:1100012307
testkey4 = WR50MS04:1100012010
testkex5 = 192.168.200.168
Run Code Online (Sandbox Code Playgroud)

并且脚本运行正常并返回ini文件的五个键.

不,我每分钟都将它配置为cronjob(在Raspberry Pi上运行rasbian)通过:

* * * * * python3 /home/pi/s0/testconfig.py >> /tmp/cron_debug_log.log 2>&1
Run Code Online (Sandbox Code Playgroud)

并且日志看起来像这样:

Traceback (most recent call last):
  File "/home/pi/s0/testconfig.py", line 7, in <module>
    for key in config['test_section']: print(key)
  File "/usr/lib/python3.2/configparser.py", line 941, in __getitem__
    raise KeyError(key)
KeyError: 'test_section'
Run Code Online (Sandbox Code Playgroud)

有谁知道我做错了亲切的问候

cron configparser python-3.x

5
推荐指数
1
解决办法
5271
查看次数

计算所有 .class 文件

我想统计.class项目目录中的所有文件。我正在ubuntu上工作。我可以像这样列出所有类文件 -

find . -type f -name '*.class'
Run Code Online (Sandbox Code Playgroud)

它列出了很多.class文件。但我想知道这些文件的数量.class。有没有办法在linux下做到这一点。

谢谢。

linux bash shell count

5
推荐指数
1
解决办法
1129
查看次数

Python“请求”在线程中不起作用/阻塞?

我已经requests在 python 2.7 中尝试过这个模块并且非常喜欢它,但是当我尝试在一个线程中使用它时,它似乎不起作用:

def doWork():
    try:
        print "before"
        requests.get('http://www.google.fr')
        print "after"
    except Exception as e:
        print "Error : "+ str(e)

# Working : I see "before" & "after"
doWork()

# Not working, i see "before" but never "after"
t = Thread(target=doWork)
t.start()
Run Code Online (Sandbox Code Playgroud)

我试过这种方式,但它是一样的:

class TestThread(Thread):
    def run(self):
        try:
            print "before"
            requests.get('http://www.google.fr')
            print "after"
        except Exception as e:
            print "Error : "+ str(e)

test_thread = TestThread()
test_thread.start() # I will see "before" but never "after"
test_thread.join()
Run Code Online (Sandbox Code Playgroud)

我试图等待几分钟(几小时),但它仍然无法正常工作;既没有after …

python multithreading visual-studio python-requests

5
推荐指数
1
解决办法
1482
查看次数