### HTTP Client with WASI Source: https://context7.com/libraries/pywasm/llms.txt Example of running a WASI program that makes HTTP requests, demonstrating directory mapping and output capture. ```APIDOC ## Complete Example - HTTP Client with WASI ### Description This example demonstrates running a WASI program that makes HTTP requests, with proper directory mapping and output capture. ### Method N/A (Illustrative Code) ### Endpoint N/A ### Parameters N/A ### Request Example ```python import io import pywasm runtime = pywasm.core.Runtime() # Set up WASI with directory access for any required files wasi = pywasm.wasi.Preview1( ['wasi_httpbin.wasm'], # Program name as first argument {'.': '.'}, # Map current directory {} # No environment variables needed ) # Capture stdout to retrieve HTTP response wasi.fd[1].pipe = io.BytesIO(bytearray()) wasi.bind(runtime) module = runtime.instance_from_file('example/wasi_httpbin/bin/wasi_httpbin.wasm') exit_code = wasi.main(runtime, module) # Read and process the response wasi.fd[1].pipe.seek(0) response = wasi.fd[1].pipe.read() print(f'HTTP Response:\n{response.decode()}') print(f'Exit code: {exit_code}') ``` ### Response N/A (Illustrative Output) #### Success Response (200) N/A #### Response Example ``` HTTP Response: [Content of the HTTP response] Exit code: 0 ``` ``` -------------------------------- ### Install Pywasm using pip Source: https://github.com/libraries/pywasm/blob/master/README.md This command installs the Pywasm library using pip, making it available for use in Python projects. Ensure you have Python 3.12 or higher installed. ```shell pip install pywasm ``` -------------------------------- ### Run Pywasm Tests Source: https://github.com/libraries/pywasm/blob/master/README.md These shell commands execute various test suites for the Pywasm library. They cover example functionalities, main library features, WebAssembly specification compliance, and WASI compatibility. Ensure the build scripts are run first to download dependencies. ```shell python test/example.py python test/main.py python test/spec.py python test/wasi.py ``` -------------------------------- ### Initialize and Run WASI Preview 1 Source: https://context7.com/libraries/pywasm/llms.txt Demonstrates how to initialize the WASI Preview 1 environment with arguments, directory mappings, and environment variables, then bind and execute a WebAssembly module. ```python import pywasm runtime = pywasm.core.Runtime() # Initialize WASI with command-line args, directory mappings, and environment variables wasi = pywasm.wasi.Preview1( ['program_name.wasm', 'arg1', 'arg2'], # Command-line arguments {'.': '.'}, # Directory pre-opens: {wasm_path: host_path} {'HOME': '/home/user', 'PATH': '/bin'} # Environment variables ) # Bind WASI imports to the runtime wasi.bind(runtime) # Load and run the WASI application module = runtime.instance_from_file('example/wasi_ll/bin/wasi_ll.wasm') exit_code = wasi.main(runtime, module) print(f'Program exited with code: {exit_code}') ``` -------------------------------- ### Instantiate WebAssembly Module from File Source: https://context7.com/libraries/pywasm/llms.txt Demonstrates how to initialize a WebAssembly runtime and load a module from a local .wasm file. This is the entry point for executing any WebAssembly code. ```python import pywasm # Create a runtime instance runtime = pywasm.core.Runtime() # Load and instantiate a WebAssembly module from file module = runtime.instance_from_file('example/fibonacci/bin/fibonacci.wasm') # The module is now ready to use print(f"Module instantiated successfully") ``` -------------------------------- ### Execute WASI Programs with I/O Capture Source: https://context7.com/libraries/pywasm/llms.txt Illustrates how to run a WASI-compatible module, map directories for file access, and capture standard output using an io.BytesIO stream. This is useful for programs that perform network or file operations. ```python import io import pywasm runtime = pywasm.core.Runtime() wasi = pywasm.wasi.Preview1(['wasi_httpbin.wasm'], {'.': '.'}, {}) wasi.fd[1].pipe = io.BytesIO(bytearray()) wasi.bind(runtime) module = runtime.instance_from_file('example/wasi_httpbin/bin/wasi_httpbin.wasm') exit_code = wasi.main(runtime, module) wasi.fd[1].pipe.seek(0) response = wasi.fd[1].pipe.read() print(f'HTTP Response:\n{response.decode()}') print(f'Exit code: {exit_code}') ``` -------------------------------- ### Memory Operations Source: https://context7.com/libraries/pywasm/llms.txt Demonstrates how to write and read byte arrays to and from WebAssembly memory, and how to check memory size. ```APIDOC ## Memory Operations ### Description Write and read byte arrays to/from WebAssembly memory. Also shows how to get the current memory size. ### Method N/A (Illustrative Code) ### Endpoint N/A ### Parameters N/A ### Request Example ```python import pywasm # Assuming 'runtime' and 'memory' are initialized # For example: # runtime = pywasm.core.Runtime() # module = runtime.instance_from_file('path/to/your/module.wasm') # memory = runtime.exports(module)['memory'] # If memory is exported address = 0 # Example address data = bytearray(b'Hello, WebAssembly!') memory.put(address + 16, data) read_data = memory.get(address + 16, len(data)) print(f'String: {read_data.decode()}') # Memory size operations current_pages = memory.size # Size in 64KB pages print(f'Memory size: {current_pages} pages ({current_pages * 64}KB)') ``` ### Response N/A (Illustrative Output) #### Success Response (200) N/A #### Response Example ``` String: Hello, WebAssembly! Memory size: X pages (YKB) ``` ``` -------------------------------- ### Define WebAssembly Value Types Source: https://context7.com/libraries/pywasm/llms.txt Illustrates how to create WebAssembly value types and function signatures using pywasm.core.ValType and FuncType. ```python import pywasm # Create value types for function signatures i32_type = pywasm.core.ValType.i32() # 32-bit integer i64_type = pywasm.core.ValType.i64() # 64-bit integer f32_type = pywasm.core.ValType.f32() # 32-bit float f64_type = pywasm.core.ValType.f64() # 64-bit float v128_type = pywasm.core.ValType.v128() # 128-bit SIMD vector # Create function type: (i32, i32) -> i32 func_type = pywasm.core.FuncType( [pywasm.core.ValType.i32(), pywasm.core.ValType.i32()], # Parameters [pywasm.core.ValType.i32()] # Results ) print(f'Function signature: {func_type}') ``` -------------------------------- ### Provide WASI Input via Stdin Source: https://context7.com/libraries/pywasm/llms.txt Demonstrates how to provide input data to a WASI program by piping a BytesIO object into the stdin file descriptor. ```python import io import pywasm runtime = pywasm.core.Runtime() wasi = pywasm.wasi.Preview1(['program.wasm'], {}, {}) # Provide input data via stdin input_data = b'Hello from Python!\n' wasi.fd[0].pipe = io.BytesIO(input_data) # Capture stdout wasi.fd[1].pipe = io.BytesIO(bytearray()) wasi.bind(runtime) module = runtime.instance_from_file('path/to/program.wasm') wasi.main(runtime, module) ``` -------------------------------- ### Perform Memory Operations Source: https://context7.com/libraries/pywasm/llms.txt Demonstrates reading and writing various data types directly to WebAssembly linear memory using MemInst. ```python import pywasm runtime = pywasm.core.Runtime() module = runtime.instance_from_file('example/blake2b/bin/blake2b.wasm') memory = runtime.exported_memory(module, 'memory') # Write various data types to memory address = 1024 # Memory address # Write/read integers memory.put_i32(address, -12345) value_i32 = memory.get_i32(address) print(f'i32 at {address}: {value_i32}') memory.put_u32(address + 4, 0xDEADBEEF) value_u32 = memory.get_u32(address + 4) print(f'u32 at {address + 4}: {hex(value_u32)}') memory.put_i64(address + 8, -9876543210) value_i64 = memory.get_i64(address + 8) print(f'i64 at {address + 8}: {value_i64}') ``` -------------------------------- ### Build Pywasm Testing Dependencies Source: https://github.com/libraries/pywasm/blob/master/README.md These shell commands are used to download necessary tools and test suites for Pywasm. 'build_wabt.py' downloads wabt tools, 'build_spec.py' downloads WebAssembly spec tests, and 'build_wasi.py' downloads WASI test suites. These are prerequisites for running Pywasm's tests. ```shell python script/build_wabt.py python script/build_spec.py python script/build_wasi.py ``` -------------------------------- ### Capture WASI Output Source: https://context7.com/libraries/pywasm/llms.txt Shows how to redirect WASI stdout to a BytesIO buffer to capture and process program output programmatically. ```python import io import pywasm runtime = pywasm.core.Runtime() wasi = pywasm.wasi.Preview1(['wasi_stdout.wasm'], {}, {}) # Redirect stdout to a BytesIO buffer for capture wasi.fd[1].pipe = io.BytesIO(bytearray()) wasi.bind(runtime) module = runtime.instance_from_file('example/wasi_stdout/bin/wasi_stdout.wasm') wasi.main(runtime, module) # Read captured output wasi.fd[1].pipe.seek(0) output = wasi.fd[1].pipe.read() print(f'Captured output: {output}') ``` -------------------------------- ### Convert Runtime Values Source: https://context7.com/libraries/pywasm/llms.txt Explains how to convert between Python native types and WebAssembly runtime value instances using ValInst. ```python import pywasm # Create value instances from Python types val_i32 = pywasm.core.ValInst.from_i32(42) val_i64 = pywasm.core.ValInst.from_i64(9876543210) val_f32 = pywasm.core.ValInst.from_f32(3.14) val_f64 = pywasm.core.ValInst.from_f64(2.718281828) # Convert back to Python types print(f'i32 value: {val_i32.into_i32()}') print(f'i64 value: {val_i64.into_i64()}') print(f'f32 value: {val_f32.into_f32()}') print(f'f64 value: {val_f64.into_f64()}') # Create SIMD v128 vectors v128_i32x4 = pywasm.core.ValInst.from_v128_i32([1, 2, 3, 4]) v128_f32x4 = pywasm.core.ValInst.from_v128_f32([1.0, 2.0, 3.0, 4.0]) # Extract SIMD lanes lanes = v128_i32x4.into_v128_i32() print(f'v128 i32x4 lanes: {lanes}') ``` -------------------------------- ### Register Python Host Functions Source: https://context7.com/libraries/pywasm/llms.txt Explains how to expose Python functions to WebAssembly modules by registering them as host functions. This requires defining the function signature using FuncType. ```python import pywasm def fibonacci(n: int) -> int: if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2) def fibonacci_host(_: pywasm.core.Machine, args: list[int]) -> list[int]: return [fibonacci(args[0])] runtime = pywasm.core.Runtime() # Register the host function with explicit type signature runtime.imports['env'] = {} runtime.imports['env']['fibonacci_host'] = runtime.allocate_func_host( pywasm.core.FuncType( [pywasm.core.ValType.i32()], [pywasm.core.ValType.i32()] ), fibonacci_host, ) module = runtime.instance_from_file('example/fibonacci_env/bin/fibonacci_env.wasm') result = runtime.invocate(module, 'fibonacci', [10]) print(f'fibonacci(10) = {result[0]}') ``` -------------------------------- ### Instantiate and Invoke WebAssembly Module in Python Source: https://github.com/libraries/pywasm/blob/master/README.md This Python code snippet demonstrates how to instantiate a WebAssembly module from a file and invoke a function within it using the Pywasm library. It requires a pre-compiled .wasm file, such as 'fibonacci.wasm'. The output is the result of the invoked function. ```python import pywasm pywasm.log.lvl = 1 runtime = pywasm.core.Runtime() m = runtime.instance_from_file('example/fibonacci/bin/fibonacci.wasm') r = runtime.invocate(m, 'fibonacci', [10]) print(f'fibonacci(10) = {r[0]}') ``` -------------------------------- ### Manage WebAssembly Memory in Python Source: https://context7.com/libraries/pywasm/llms.txt Demonstrates how to read and write byte arrays to WebAssembly memory and retrieve the current memory size in pages. These operations are essential for passing data between the Python host and the WASM module. ```python data = bytearray(b'Hello, WebAssembly!') memory.put(address + 16, data) read_data = memory.get(address + 16, len(data)) print(f'String: {read_data.decode()}') current_pages = memory.size print(f'Memory size: {current_pages} pages ({current_pages * 64}KB)') ``` -------------------------------- ### Access Exported Global Variables Source: https://context7.com/libraries/pywasm/llms.txt Demonstrates how to retrieve global variables defined and exported by a WebAssembly module for inspection or modification. ```python import pywasm runtime = pywasm.core.Runtime() module = runtime.instance_from_file('path/to/module.wasm') # Get an exported global variable global_inst = runtime.exported_global(module, 'counter') ``` -------------------------------- ### Invoke Exported WebAssembly Functions Source: https://context7.com/libraries/pywasm/llms.txt Shows how to call functions exported by a WebAssembly module using the invocate method. It accepts a list of arguments and returns a list of results. ```python import pywasm runtime = pywasm.core.Runtime() module = runtime.instance_from_file('example/fibonacci/bin/fibonacci.wasm') # Call the exported 'fibonacci' function with argument 10 result = runtime.invocate(module, 'fibonacci', [10]) # Result is a list of return values print(f'fibonacci(10) = {result[0]}') ``` -------------------------------- ### Configure Pywasm Logging Source: https://context7.com/libraries/pywasm/llms.txt Shows how to enable or disable debug logging in Pywasm. Setting the log level to 1 provides detailed output during module parsing and instruction execution. ```python import pywasm pywasm.log.lvl = 1 runtime = pywasm.core.Runtime() module = runtime.instance_from_file('example/fibonacci/bin/fibonacci.wasm') result = runtime.invocate(module, 'fibonacci', [5]) pywasm.log.lvl = 0 ``` -------------------------------- ### Access Exported WebAssembly Memory Source: https://context7.com/libraries/pywasm/llms.txt Illustrates how to read from and write to WebAssembly linear memory. This is essential for passing complex data structures between Python and WebAssembly. ```python import pywasm runtime = pywasm.core.Runtime() module = runtime.instance_from_file('example/blake2b/bin/blake2b.wasm') # Get the exported memory instance memory = runtime.exported_memory(module, 'memory') # Prepare input data data = bytearray(b'abc') data_size = len(data) # Allocate memory in WebAssembly for input and output data_ptr = runtime.invocate(module, 'alloc', [data_size])[0] hash_size = 64 hash_ptr = runtime.invocate(module, 'alloc', [hash_size])[0] # Write data to WebAssembly memory memory.put(data_ptr, data) # Execute the hash function runtime.invocate(module, 'blake2b', [data_ptr, data_size, hash_ptr, hash_size]) # Read the result from WebAssembly memory hash_result = memory.get(hash_ptr, hash_size) print(f'BLAKE2b hash: {hash_result.hex()}') ``` -------------------------------- ### Logging Configuration Source: https://context7.com/libraries/pywasm/llms.txt Configures the logging level for Pywasm to enable or disable debug output during module execution. ```APIDOC ## Logging Configuration ### Description Pywasm includes a configurable logging system for debugging WebAssembly execution. Set the log level to see detailed information about module parsing and instruction execution. ### Method N/A (Illustrative Code) ### Endpoint N/A ### Parameters N/A ### Request Example ```python import pywasm # Set log level (0 = silent, 1 = debug output) pywasm.log.lvl = 1 runtime = pywasm.core.Runtime() # Now module loading and execution will print debug information module = runtime.instance_from_file('example/fibonacci/bin/fibonacci.wasm') result = runtime.invocate(module, 'fibonacci', [5]) # Disable logging pywasm.log.lvl = 0 ``` ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.