小编San*_*nta的帖子

Ruby:捕获异常后继续循环

基本上,我想做这样的事情(用Python或类似的命令式语言):

for i in xrange(1, 5):
    try:
        do_something_that_might_raise_exceptions(i)
    except:
        continue    # continue the loop at i = i + 1
Run Code Online (Sandbox Code Playgroud)

我如何在Ruby中执行此操作?我知道有redoretry关键字,但它们似乎重新执行"try"块,而不是继续循环:

for i in 1..5
    begin
        do_something_that_might_raise_exceptions(i)
    rescue
        retry    # do_something_* again, with same i
    end
end
Run Code Online (Sandbox Code Playgroud)

ruby loops exception-handling

63
推荐指数
3
解决办法
4万
查看次数

将HG项目从Bitbucket镜像到Github

是否有一个高效的工作流来镜像主要使用Hg托管在bitbucket上的项目到github?

git workflow mercurial github bitbucket

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

Python2.7中的StringIO和io.StringIO有什么区别?

除了明显的(一个是类型,另一个类)?什么应该是首选?用例中的任何显着差异,也许?

python string

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

Python distutils错误:"[目录] ...不存在或不是常规文件"

我们采取以下项目布局:

$ ls -R .
.:
package  setup.py

./package:
__init__.py  dir  file.dat  module.py

./package/dir:
tool1.dat  tool2.dat
Run Code Online (Sandbox Code Playgroud)

以下内容为setup.py:

$ cat setup.py 
from distutils.core import setup


setup(name='pyproj',
      version='0.1',

      packages=[
          'package',
      ],
      package_data={
          'package': [
              '*',
              'dir/*',
          ],
      },
     )
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我想在所有非Python文件package/package/dir/目录.但是,运行setup.py install会引发以下错误:

$ python setup.py install
running install
running build
running build_py
creating build
creating build/lib
creating build/lib/package
copying package/module.py -> build/lib/package
copying package/__init__.py -> build/lib/package
error: can't copy 'package/dir': doesn't exist or not a …
Run Code Online (Sandbox Code Playgroud)

python distutils

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

Python文件解析:从文本文件构建树

我有一个缩进的文本文件,将用于构建一个树.每行代表一个节点,缩进代表深度以及当前节点是其子节点的节点.

例如,文件可能看起来像

ROOT
   Node1
      Node2
         Node3
            Node4
   Node5
   Node6

这表明ROOT包含三个子节点:1,5和6,Node1有一个子节点:2,Node2有一个子节点:3,等等.

我已经提出了一个递归算法并对它进行了编程并且它可以正常工作,但它有点难看,特别是对上面的例子非常粗略(从节点4到节点5)

它使用"缩进计数"作为递归的基础,因此如果缩进的数量=当前深度+ 1,我会更深一层.但这意味着当我读取一个较少缩进的行时,我必须一次返回一个级别,每次检查深度.

这就是我所拥有的

def _recurse_tree(node, parent, depth):
    tabs = 0

    while node:
        tabs = node.count("\t")
        if tabs == depth:
            print "%s: %s" %(parent.strip(), node.strip())
        elif tabs == depth + 1:
            node = _recurse_tree(node, prev, depth+1)
            tabs = node.count("\t")

            #check if we have to surface some more
            if tabs == depth:
                print "%s: %s" %(parent.strip(), node.strip())
            else:
                return node
        else:
            return node

        prev = node
        node = inFile.readline().rstrip()

inFile = …

python algorithm tree recursion

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

nose,unittest.TestCase和metaclass:未发现自动生成的test_*方法

这是unittest和元类的后续问题:自动test_*方法生成:

对于这个(固定的)unittest.TestCase布局:

#!/usr/bin/env python

import unittest


class TestMaker(type):

    def __new__(cls, name, bases, attrs):
        callables = dict([
            (meth_name, meth) for (meth_name, meth) in attrs.items() if
            meth_name.startswith('_test')
        ])

        for meth_name, meth in callables.items():
            assert callable(meth)
            _, _, testname = meth_name.partition('_test')

            # inject methods: test{testname}_v4,6(self)
            for suffix, arg in (('_false', False), ('_true', True)):
                testable_name = 'test{0}{1}'.format(testname, suffix)
                testable = lambda self, func=meth, arg=arg: func(self, arg)
                attrs[testable_name] = testable

        return type.__new__(cls, name, bases, attrs)


class TestCase(unittest.TestCase):

    __metaclass__ = TestMaker

    def …
Run Code Online (Sandbox Code Playgroud)

python unit-testing metaclass nose

12
推荐指数
1
解决办法
1794
查看次数

Python:Unicode和ElementTree.parse

我正在尝试迁移到Python 2.7,因为Unicode在那里是一个大交易,我会尝试用XML文件和文本处理它们并使用xml.etree.cElementTree库解析它们.但我碰到了这个错误:

>>> import xml.etree.cElementTree as ET
>>> from io import StringIO
>>> source = """\
... <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
... <root>
...   <Parent>
...     <Child>
...       <Element>Text</Element>
...     </Child>
...   </Parent>
... </root>
... """
>>> srcbuf = StringIO(source.decode('utf-8'))
>>> doc = ET.parse(srcbuf)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 56, in parse
  File "<string>", line 35, in parse
cElementTree.ParseError: no element found: line 1, column 0
Run Code Online (Sandbox Code Playgroud)

使用 …

python xml unicode python-3.x

10
推荐指数
3
解决办法
3万
查看次数

检查链接列表是否加入以开始

我正在尝试检查链表的最后一个节点是否指向头部.此代码似乎为问题提供了积极的结果,但也为包含指向非头节点的节点的列表提供了误报.

我一直在尝试不同的事情,例如检查慢节点是否等于返回真实点的头部,但这似乎不起作用.

public boolean isLinkedToStart(Node head) {
    if (head == null) {
        return false;
    }
    Node fast = head.next;
    Node slow = head;
    while (fast != null && fast.next != null) {
        if (fast.next.next == slow) {
            return true;
        }
        fast = fast.next.next;
        slow = slow.next;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

有什么建议?

java linked-list

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

Windows中的临时PYTHONPATH

如何在执行Python脚本之前临时设置PYTHONPATH环境变量?

在*nix中,我可以这样做:

$ PYTHONPATH='.' python scripts/doit.py
Run Code Online (Sandbox Code Playgroud)

在Windows中,当然这种语法不起作用.但是等价物是什么?

python windows command-line

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

Mercurial subrepo和相对路径

我有一个项目,我有一个bitbucket存储库,它依赖于我作为subrepo合并的另一个项目.现在,我没有对子存储库的推送访问权限,也没有我想要或不需要的权限 - 这是一种只有拉动的关系.

我意识到当你推送主存储库时,它也会尝试推送子存储库.由于我无法做到这一点,因此我提取了依赖项目的本地副本,与主存储库目录处于同一级别.从本质上讲,我有以下布局:

Main/           ; pushes to https://mine.org/Main
  .hg/
  .hgsub
  Lib/
    SubRepo/    ; clone of Main/../SubRepo/
      .hg/

SubRepo/        ; local copy of https://forbidden.org/SubRepo
  .hg/
Run Code Online (Sandbox Code Playgroud)

内容.hgsub是这样的,

Lib/SubRepo = ../SubRepo
Run Code Online (Sandbox Code Playgroud)

然后我克隆了,

~/path/to/Main $ hg clone ../SubRepo/ Lib/SubRepo
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.问题是,在我设置了全部并提交了更改之后,当我尝试推送Main Mercurial时会尝试将SubRepo推送到https://mine.org/SubRepo,这不存在,从而导致整个推送操作失败.

有什么我想念的吗?

mercurial relative-path mercurial-subrepos

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