小编cul*_*rón的帖子

从traceback获取最后一个函数的调用参数?

我可以获取traceback中调用的最后一个函数的参数吗?怎么样?

我想制作标准错误的捕获器以生成可读代码,同时向用户提供详细信息.

在下面的例子中,我希望GET_PARAMS返回一个提供给os.chown的参数元组.检查inspectAlex Martelli建议的模块,我找不到.

def catch_errors(fn):
    def decorator(*args, **kwargs):
        try:
            return fn(*args, **kwargs)
        except (IOError, OSError):
            msg = sys.exc_info()[2].tb_frame.f_locals['error_message']
            quit(msg.format(SEQUENCE_OF_PARAMETERS_OF_THE_LAST_FUNCTION_CALLED)\
            + '\nError #{0[0]}: {0[1]}'.format(sys.exc_info()[1].args), 1)
    return decorator

@catch_errors
def do_your_job():
    error_message = 'Can\'t change folder ownership \'{0}\' (uid:{1}, gid:{2})'
    os.chown('/root', 1000, 1000) # note that params aren't named vars.

if __name == '__main__' and os.getenv('USERNAME') != 'root':
    do_your_job()
Run Code Online (Sandbox Code Playgroud)

(感谢Jim Robert为装饰师)

python exception-handling traceback

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

如何利用Python中的线程解析大文件?

我有一个巨大的文件,需要阅读和处理.

with open(source_filename) as source, open(target_filename) as target:
    for line in source:
        target.write(do_something(line))

    do_something_else()
Run Code Online (Sandbox Code Playgroud)

这可以通过线程加速吗?如果我每行产生一个线程,这会产生巨大的开销吗?

编辑:为了使这个问题不是讨论,代码应该如何?

with open(source_filename) as source, open(target_filename) as target:
   ?
Run Code Online (Sandbox Code Playgroud)

@Nicoretti:在迭代中,我需要读取一行数KB的数据.

更新2:文件可能是bz2,因此Python可能必须等待解压缩:

$ bzip2 -d country.osm.bz2 | ./my_script.py
Run Code Online (Sandbox Code Playgroud)

python parallel-processing multithreading large-files

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

如何避免重复异常处理?

我已经将IOError处理移动到一个单独的函数,以避免在打开文件进行读取时出现样板.

但是如果在读取文件时IOError会触发怎么办?如果sshfs断开连接,或者文件被root删除等?

def safe_open(*args):
    try:
        return open(*args)
    except IOError:
        quit('Error when opening file \'{0}\'. Error #{1[0]}: {1[1]}'.format(\
        args[0], sys.exc_info()[1].args))
Run Code Online (Sandbox Code Playgroud)

...

with safe_open(myfile, 'r') as f:
    for i in f:
        print i

with safe_open(anotherfile, 'r') as f:
    try:
        conf = ''.join(f).format(**args)
    except KeyError:
        quit('\nOops, your template \'{0}\' has placeholders for' + \
        'parameters\nthat were not supplied in the command line: - {1}\n' +
        '\nCan\'t proceed. Ending. Nothing has been changed yet.'.format( \
        args['host_template'], '\n - '.join(sys.exc_info()[1].args)), 1)
Run Code Online (Sandbox Code Playgroud)

文件以不同的方式读取,所以我没有看到将它放入函数并将更改的部分作为参数传递的方法.

[补充:想到这个解决方案,但它使一个无法关闭的发电机.如果循环停止,则文件保持打开状态.]

def reader(*args): …
Run Code Online (Sandbox Code Playgroud)

python exception-handling

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

如何在地图中将项目作为args列表传递?

这是我的一段代码.Lambda接受3个参数,我想将它们作为位置参数的元组传递,但显然map将它们作为单个参数提供.

我如何在底部提供这些元组作为参数列表?(我知道我可以重写lambda,但它会变得不易阅读)

 adds = map((lambda j, f, a:
      j.join([f.format(i) for i in parse.options[a]]) if parse.options[a] else ''),
      ((' ', ' -not -path "{0}" ', 'exclude'),
      (' -or ', '-path "{0}"', 'include')))
Run Code Online (Sandbox Code Playgroud)

python arguments map

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

为什么PostgreSQL以错误的方式组合系列?

我得到了一些组合generate_series的奇怪行为.在我试图用网格填充的2个不同的多边形中,一个网格非常罕见:

在此输入图像描述

查询是这样的:

SELECT
    osm_id ,
        generate_series(floor(st_xmin(way))::int, ceiling(st_xmax(way))::int, 150) x,
        generate_series(floor(st_ymin(way))::int, ceiling(st_ymax(way))::int, 150) y 
from osm_polygon
order by osm_id, x, y;
Run Code Online (Sandbox Code Playgroud)

我试着追踪问题,只输入了最小/最大坐标.从最小值/最大值生成序列创建正确的值数:分别为9行和12行.

  => select generate_series(9237195, 9238873, 150) x;
      x    
  ---------
   9237195
   9237345
   9237495
   9237645
   9237795
   9237945
   9238095
   9238245
   9238395
   9238545
   9238695
   9238845
  (12 rows)

  => select generate_series(7371701, 7372922, 150) y order by y;
      y    
  ---------
   7371701
   7371851
   7372001
   7372151
   7372301
   7372451
   7372601
   7372751
   7372901
  (9 rows)
Run Code Online (Sandbox Code Playgroud)

结合起来,他们应该制作108排吧?不,只有36行:

=> select generate_series(9237195, 9238873, 150) x, generate_series(7371701, 7372922, 150) y order by x, y; …
Run Code Online (Sandbox Code Playgroud)

postgresql combinations postgis generate-series

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

如何在一个SQL查询中插入多个项目?

我有20件物品.是否可以只使用一个查询插入20个项目(没有循环)?

mysql sql

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

这些解压有必要吗?

我是 Rust 新手,我看到很多代码如下所示:

use std::thread;

fn main() {
    println!("So we start the program here!");
    let t1 = thread::spawn(move || {
        thread::sleep(std::time::Duration::from_millis(200));
        println!("We create tasks which gets run when they're finished!");
    });

    let t2 = thread::spawn(move || {
        thread::sleep(std::time::Duration::from_millis(100));
        println!("We can even chain callbacks...");
        let t3 = thread::spawn(move || {
            thread::sleep(std::time::Duration::from_millis(50));
            println!("...like this!");
        });
        t3.join().unwrap();
    });
    println!("While our tasks are executing we can do other stuff here.");

    t1.join().unwrap();
    t2.join().unwrap();
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,他们调用join()后跟unwrap(),但他们不使用未包装的东西。我尝试删除这些unwrap(),它仍然有效。这些有unwrap()必要吗?我还注意到甚至 Rust 书也使用这种语法。

multithreading rust

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