Run Your First Simulation with the Python SDK
This page provides the shortest and replicable SDK link: log in to the platform, select the workspace and personal model you have access to, start the job, wait for the final state, and then read the final log and a trend chart result.
The example gives priority to running a model that already exists and has been verified on the page. In this way, you can first confirm that the SDK, account, job channel, and simulation kernel can all work together normally before starting to write automatic modeling code. Different workspaces have different component types, ports, and required parameters, which makes it unsuitable to replace the existing model with an unconfirmed set of "universal minimum topology."
Prepare Environment
The following conditions need to be met:
- Python 3.10 or higher;
- The current public package has been installed:
python -m pip install nexusflow-sdk; - The account can log in to the target platform and has access to at least one workspace;
- There is at least one working saved model belonging to the current account.
Put the connection information in the environment variables of the current process or the key store of the continuous integration system, do not write it into the script:
| Environment Variables | Required | Description |
|---|---|---|
NEXUSFLOW_BASE_URL | Yes | Platform root address, do not append /api/, Workbench path or fixed model path |
NEXUSFLOW_USERNAME | Yes | User name or complete email address bound to the account |
NEXUSFLOW_PASSWORD | Yes | Login password; use terminal secure entry or key storage injection, do not submit to repository |
NEXUSFLOW_WORKSPACE_TYPE | No | workspace type; if not set, select the first item in the list accessible to the current account |
NEXUSFLOW_MODEL_ID | No | Model UUID to run; when not set selects the first personal model in the target space |
NEXUSFLOW_JOB_TIMEOUT_SECONDS | No | The running timeout submitted to the job, the example default is 300 seconds |
NEXUSFLOW_WAIT_TIMEOUT_SECONDS | No | The maximum time the script waits for the job to enter the final state, the example default is 600 seconds |
NEXUSFLOW_STOP_ON_EXIT | No | Whether to stop still running jobs when exiting abnormally, default true |
It is recommended to set the workspace and model ID explicitly so that the same script runs the same target every time. Do not print passwords, access tokens, or the full list of environment variables to the log.
For authentication and token storage methods, see Install and Authenticate the Python SDK.
Complete Example
Save the following code as first_simulation.py and run it in the terminal where the above environment variables have been configured:
from __future__ import annotations
import os
from nexusflow_sdk import Model, NexusFlowClient, ResultExpiredError
def require_env(name: str) -> str:
value = os.getenv(name, "").strip()
if not value:
raise RuntimeError(f"缺少环境变量:{name}")
return value
def positive_float_env(name: str, default: float) -> float:
raw = os.getenv(name)
value = default if raw is None else float(raw)
if value <= 0:
raise ValueError(f"{name} 必须大于 0")
return value
def positive_int_env(name: str, default: int) -> int:
raw = os.getenv(name)
value = default if raw is None else int(raw)
if value <= 0:
raise ValueError(f"{name} 必须是大于 0 的整数")
return value
def env_flag(name: str, default: bool) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return raw.strip().lower() not in {"0", "false", "no", "off"}
def workspace_types(client: NexusFlowClient) -> list[str]:
items = client.meta.list_workspace_types(scope="access")
return [
str(item["type"])
for item in items
if isinstance(item, dict) and item.get("type")
]
def choose_workspace(client: NexusFlowClient) -> str:
accessible = workspace_types(client)
if not accessible:
raise RuntimeError("当前账号没有可访问的工作台空间")
requested = os.getenv("NEXUSFLOW_WORKSPACE_TYPE", "").strip()
if requested:
if requested not in accessible:
raise RuntimeError(f"当前账号不能访问工作台空间:{requested}")
return requested
return accessible[0]
def choose_model(client: NexusFlowClient, workspace_type: str) -> Model:
model_id = os.getenv("NEXUSFLOW_MODEL_ID", "").strip()
if model_id:
model = client.get_model(model_id)
if model.workspace_type != workspace_type:
raise RuntimeError(
f"模型属于 {model.workspace_type},不是目标空间 {workspace_type}"
)
return model
models = client.list_models(
query_type="my_models",
type=workspace_type,
page=1,
page_size=1,
)
if not models:
raise RuntimeError(
"目标空间中没有个人模型;请先在页面中保存一个可运行模型,"
"或设置 NEXUSFLOW_MODEL_ID"
)
return models[0]
def main() -> None:
base_url = require_env("NEXUSFLOW_BASE_URL")
username = require_env("NEXUSFLOW_USERNAME")
password = require_env("NEXUSFLOW_PASSWORD")
job_timeout = positive_int_env("NEXUSFLOW_JOB_TIMEOUT_SECONDS", 300)
wait_timeout = positive_float_env(
"NEXUSFLOW_WAIT_TIMEOUT_SECONDS", 600
)
stop_on_exit = env_flag("NEXUSFLOW_STOP_ON_EXIT", True)
client = NexusFlowClient(base_url=base_url, timeout=30)
job = None
try:
# 显式登录,尽早发现账号或密码问题。
client.login(username, password)
workspace_type = choose_workspace(client)
model = choose_model(client, workspace_type)
print(
f"使用工作台空间 {workspace_type},"
f"模型 {model.name} ({model.id})"
)
# run() 默认也会校验;这里显式写出,便于阅读。
job = model.run(timeout=job_timeout, validate=True)
print(f"任务已创建:{job.id},当前状态:{job.status}")
# 必须传入 timeout,避免脚本无限轮询。
job.wait(timeout=wait_timeout, poll_interval=2)
print(f"任务进入终态:{job.status},进度:{job.progress}")
# 只读取末尾一段结果,避免首次运行就下载很大的完整结果流。
results = job.get_tail_results(count=500, timeout=5)
logs = results.logs()
print(f"读取到 {len(logs)} 条末尾日志")
for item in logs[-10:]:
print(f"[{item.level}] {item.message}")
plots = results.plots()
if plots:
result_key, plot = next(iter(plots.items()))
print(
f"读取到趋势图 {result_key},"
f"配置字段:{sorted(plot.config.keys())}"
)
else:
print("该任务的末尾结果中没有趋势图")
if job.status != "success":
raise RuntimeError(f"任务未成功完成,终态为:{job.status}")
except ResultExpiredError as exc:
raise RuntimeError("任务记录仍存在,但结果流已经过期") from exc
finally:
# 默认只处理尚未终止的任务,不删除模型或已完成任务记录。
if job is not None and not job.is_terminal:
if stop_on_exit:
try:
job.stop()
print(f"已向未完成任务 {job.id} 发送停止请求")
except Exception as cleanup_error:
print(f"停止任务失败,请在任务管理中检查 {job.id}: {cleanup_error}")
else:
print(f"任务 {job.id} 仍在运行,请稍后自行检查")
client.close()
if __name__ == "__main__":
main()
The script does not output passwords or tokens, nor does it modify, save, or delete the selected model. It simply creates a new job with the current snapshot of the model.
What Does This Code Do
1. Create a Client and Authenticate
NexusFlowClient unified management of HTTP sessions, access tokens and refresh tokens. The example calls client.login() to log in explicitly, so the account error will be exposed before reading the model. When subsequent requests encounter an invalid access token, the SDK will refresh once and try again if the refresh conditions are met.
client.close() is located in finally and ensures that normal end, job failure and Python exception can close the network session.
2. Select Space and Model
client.meta.list_workspace_types(scope="access") only lists the workspaces available for the current account. When setting NEXUSFLOW_WORKSPACE_TYPE, the script verifies that it is indeed in this list.
There are two ways to select models:
- Set
NEXUSFLOW_MODEL_ID, open exactly a model you have access to, and check its workspace; - Without setting a model ID, selects the first item from the personal model in the target space.
It is recommended to use your own model when accessing for the first time. The visibility of shared models and job running permissions are determined by the server. Do not bypass permission checks in scripts.
If there is no model yet, please press Read, Edit, and Save Models with the SDK to create a component and topology that conforms to the target space definition, and call model.validate() before running. Only after confirming that the workspace allows empty models can you directly run the blank model created by client.create_model(); do not regard the blank model as a minimum calculation example applicable to all spaces.
3. Create Jobs
model.run(timeout=job_timeout, validate=True) will:
- Submit the current model draft to the platform for unified verification;
- Force refresh of workspace component definition;
- Create a separate job snapshot containing the current topology and component definitions;
- Returns a
Jobobject.
The timeout passed to run() is the job running timeout, not the client waiting time. Even if the model has been saved in the platform, the job is still based on the current draft in the SDK memory when run() is called.
4. Finite Waiting for Final State
job.wait(timeout=..., poll_interval=...) will refresh the job status periodically until it enters one of the following final states:
success: completed successfully;fault: Calculation failure;stopped: Stopped.
If the job does not enter the final state within NEXUSFLOW_WAIT_TIMEOUT_SECONDS, wait() will throw Python's TimeoutError. The example then goes to finally , which defaults to sending a stop request to jobs that are still not finished.
Job run timeout and script wait timeout should be set separately. The former constrains computation, the latter constrains callers to wait; don't rely on one replacing the other.
5. Read Logs and Trend Charts
job.get_tail_results(count=500, timeout=5) will first refresh the total number of job messages; when the total number of messages is available, up to 500 messages are read from the end and aggregated into ResultStream. Among them:
results.logs()returns theLogMessagelist;results.plots()returns thePlotMessagedictionary with the result key as the key;PlotMessage.configretains the trend chart configuration sent by the platform.
timeout=5 here is the WebSocket single reception timeout, not the total time limit for reading the entire result. For first verification, use the tail result to control the transmission volume; use job.get_results() when you need the full curve. See Run Jobs and Read Results with the SDK for result reading and type description.
Cleanup and Retention After Timeout
The example uses the following strategy:
- Jobs that have entered the final state are retained in the platform and are managed by the platform’s data retention policy;
- When the script exits abnormally, if the job is not terminated,
job.stop()will be called by default; - If the business requires the job to continue running after the script ends, set
NEXUSFLOW_STOP_ON_EXITtofalseand save the job ID for subsequent query; - The model is not automatically deleted because the example uses an existing model;
- The SDK does not include "delete job records" as part of this process, so do not clean up by yourself through undisclosed interfaces.
Stop requests are asynchronous control operations. The script printing "Stop request sent" does not mean that the job has entered stopped; the final status still needs to be queried in subsequent scripts or job management pages.
Next Steps
- Install and Authenticate the Python SDK: Using tokens, refresh tokens, and custom request timeouts
- Read, Edit, and Save Models with the SDK: Add component, connect port, set parameters and save
- Run Jobs and Read Results with the SDK: Streaming results, full results, mission control and running snapshots
- Batch Automation and Error Handling: Batch jobs, timeouts, retries and SDK exception classification