小编Ale*_*eph的帖子

Kotlin:Interface ...没有构造函数

我正在将我的一些Java代码转换为Kotlin,我不太了解如何实例化Kotlin代码中定义的接口.作为一个例子,我有一个接口(在Java代码中定义):

public interface MyInterface {
    void onLocationMeasured(Location location);
}
Run Code Online (Sandbox Code Playgroud)

然后在我的Kotlin代码中进一步实例化这个接口:

val myObj = new MyInterface { Log.d("...", "...") }
Run Code Online (Sandbox Code Playgroud)

它工作正常.但是,当我将MyInterface转换为Kotlin时:

interface MyInterface {
    fun onLocationMeasured(location: Location)
}
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息:Interface MyListener does not have constructors当我尝试实例化它时 - 虽然在我看来除了语法之外没有任何改变.我是否误解了Kotlin界面的工作原理?

java kotlin

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

同时观察子进程的stdout和stderr

如何同时查看长时间运行的子进程的标准输出和标准错误,在子进程生成后立即处理每一行?

我不介意使用Python3.6的异步工具来制作我希望在两个流中的每个流上的非阻塞异步循环,但这似乎无法解决问题.以下代码:

import asyncio
from asyncio.subprocess import PIPE
from datetime import datetime


async def run(cmd):
    p = await asyncio.create_subprocess_shell(cmd, stdout=PIPE, stderr=PIPE)
    async for f in p.stdout:
        print(datetime.now(), f.decode().strip())
    async for f in p.stderr:
        print(datetime.now(), "E:", f.decode().strip())

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run('''
         echo "Out 1";
         sleep 1;
         echo "Err 1" >&2;
         sleep 1;
         echo "Out 2"
    '''))
    loop.close()
Run Code Online (Sandbox Code Playgroud)

输出:

2018-06-18 00:06:35.766948 Out 1
2018-06-18 00:06:37.770187 Out 2
2018-06-18 00:06:37.770882 E: Err 1
Run Code Online (Sandbox Code Playgroud)

虽然我希望它输出如下:

2018-06-18 00:06:35.766948 Out 1
2018-06-18 …
Run Code Online (Sandbox Code Playgroud)

python subprocess python-asyncio

8
推荐指数
2
解决办法
429
查看次数

如何在PyCharm中正确注释ContextManager?

我如何注释contextmanagerPyCharm 中a的yield类型,以便它正确猜测with子句中使用的值的类型-就像它猜测fcreated in with open(...) as f是文件一样?

例如,我有一个这样的上下文管理器:

@contextlib.contextmanager
def temp_borders_file(geometry: GEOSGeometry, name='borders.json'):
    with TemporaryDirectory() as temp_dir:
        borders_file = Path(dir) / name
        with borders_file.open('w+') as f:
            f.write(geometry.json)
        yield borders_file

with temp_borders_file(my_geom) as borders_f:
    do_some_code_with(borders_f...)
Run Code Online (Sandbox Code Playgroud)

如何让PyCharm知道每个这样borders_f创建的对象都是的pathlib.Path(从而启用上的Path方法的自动完成功能border_f)?当然,我可以像# type: Path在每条with语句之后一样发表评论,但是似乎可以通过适当地注释来完成temp_border_file

我试过Pathtyping.Iterator[Path]typing.Generator[Path, None, None]作为返回类型的temp_border_file,以及增加# type: Pathborders_file上下文管理的代码中,但似乎它并不能帮助。

typing contextmanager pycharm

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

如何使用 clojure.string/replace 在前面添加反斜杠

我正在尝试使用clojure.string/replace反斜杠(如ex*mple-> ex\*mple)来转义星号和反引号等某些字符,但我无法理解该函数自己的转义规则:

如果我尝试(cs/replace "ex*mple" #"[\*`]" "\\$0"),它会按$0字面意思处理并返回ex$0mple

如果我尝试(cs/replace "ex*mple" #"[\*`]" "\\\\$0")它会添加两个斜杠:ex\\*mple.

正确的做法是什么?

regex string clojure

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