小编tim*_*ree的帖子

封送代码对象的Python exec()

我是python的新手,现在已经玩了一段时间.我一直在玩与周围的内置compile()功能,随着exec和内置simple.py.我注意到一些我似乎无法找到答案的东西.请考虑以下脚本:

def foo():
    print "Inside foo()..."

def main():
    print "This is a simple script that should count to 3."

    for i in range(1, 4):
        print "This is iteration number", i

    foo()

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

这通过以下方式运行时工作正常:

with open('simple.py', 'r') as f:
    code = f.read()
exec code
Run Code Online (Sandbox Code Playgroud)

但是,当编译成代码对象时,通过exec序列化compile(),保存到文件然后从文件中读取,反序列化marshal.dump(),并通过marshal.load()它运行错误,并foo声明全局名称dir()未定义.

我查看了给出的输出foo,当我dis.dis()编写代码时,我可以看到它有一个定义marshal.load().我也注意到,当我使用LOAD_NAME反序列化的代码对象(read via CALL_FUNCTION)时,我唯一看到的是main()和 …

python exec

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

在工作空间中编译时,dylib无法加载libstd

我有一个具有以下结构的项目:

Cargo.toml
my_script.py
my_lib:
    - Cargo.toml
    - src
my_bin:
    - Cargo.toml
    - src
Run Code Online (Sandbox Code Playgroud)

哪里:

  • my_lib 是一个Rust库 crate-type = ["dylib"]
  • my_bin 是一个Rust二进制应用程序,使用 my_lib
  • my_script.py 是Python 3脚本,也使用 my_lib

根目录Cargo.toml包含一个基本的工作区声明:

[workspace]
members = [
    "my_lib",
    "my_bin"
]
Run Code Online (Sandbox Code Playgroud)

如果我执行cargo build和,一切都会正常进行cargo run -p my_bin。问题来自Python脚本。

在此脚本中,我my_lib使用以下代码加载lib文件:

[workspace]
members = [
    "my_lib",
    "my_bin"
]
Run Code Online (Sandbox Code Playgroud)

如果我使用库目录./my_lib/target/...)中的库文件,则脚本在加载库和执行其功能时没有问题。

但是,如果我使用工作空间目录./target/...)中的库文件,则在尝试加载库时出现以下错误:

from ctypes import cdll
from sys import platform

if platform == 'darwin':
    prefix = 'lib' …
Run Code Online (Sandbox Code Playgroud)

python macos dylib rust rust-cargo

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

如何将Vec <Option <T >>转换为Option <Vec <T >>

我有一些像这样的矢量

let example1: Vec<Option<u64>> = vec![None, None, Some(2), Some(35)];
let example2: Vec<Option<u64>> = vec![Some(5), Some(19), Some(4), Some(6)];
Run Code Online (Sandbox Code Playgroud)

我想这将返回一个功能Noneexample1,但将返回Some([5, 19, 4, 6])example2.

换句话说,我想要一个函数,None如果有任何选项None,则返回,但是如果所有选项都Some将它们全部展开并返回Some.

rust

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

每次调用函数时如何访问函数的调用位置?

我想编写一个函数来访问它被调用的位置的文件和行号。

它看起来像这样:

fn main() {
    prints_calling_location(); // would print `called from line: 2`
    prints_calling_location(); // would print `called from line: 3`
}

fn prints_calling_location() {
    let caller_line_number = /* ??? */;
    println!("called from line: {}", caller_line_number);
}
Run Code Online (Sandbox Code Playgroud)

debugging rust

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

标签 统计

rust ×3

python ×2

debugging ×1

dylib ×1

exec ×1

macos ×1

rust-cargo ×1