ETS或者NAPI中怎么实现调用cmd命令呢(HarmonyOS 鸿蒙Next)
ETS或者NAPI中怎么实现调用cmd命令呢(HarmonyOS 鸿蒙Next) 大家好,现在我需要在程序中执行cmd命令来调用自己编译的执行文件,这个在openharmony下能实现吗,有什么路径吗
我现在通过如下代码进行测试,想接收ping 后的输出,但是始终接收不到
static napi_value LLMProcessInit(napi_env env, napi_callback_info info)
{
napi_value ret;
// 调用llm运行服务 打开子进程并获取标准输入输出流
// process = popen("export LD_LIBRARY_PATH=/data/libsForLLM:/lib:$LD_LIBRARY_PATH && /data/radxa_demo_Linux_aarch64/llm_demo DeepSeek-R1-Distill-Qwen-1.5B.rkllm 10000 10000","w+"); // 使用 "w+"读写模式 打开一个可读写的管道
FILE* process1 = nullptr;
process1 = popen("ping baidu.com",
"r"); // 使用 "w+"读写模式 打开一个可读写的管道
if (!process1) {
std::cerr << "Failed to open process" << std::endl;
OH_LOG_ERROR(LOG_APP, "LLMProcess open fail, error code: %{public}d", errno, LOG_ERROR, LOG_DOMAIN, LOG_TAG);
napi_create_int32(env, 1, &ret);
} else {
OH_LOG_INFO(LOG_APP, "LLMProcess Output is %{public}s", "FILE* process1 is not null", LOG_INFO, LOG_DOMAIN, LOG_TAG);
char output[512];
//前面popen返回是打开的
while (fgets(output, sizeof(output), process1) != NULL) {
std::cout << "Output: " << output;
fflush(stdout); // 强制刷新标准输出
OH_LOG_INFO(LOG_APP, "LLMProcess Output is %{public}s", output, LOG_INFO, LOG_DOMAIN, LOG_TAG);
}
// 检查是否有错误输出
if (feof(process1)) {
// 读取标准错误流(stderr)
FILE *errorStream = popen("ping baidu.com 2>&1", "r");
if (errorStream) {
while (fgets(output, sizeof(output), errorStream) != NULL) {
std::cerr << "Error Output: " << output;
}
fclose(errorStream);
}
}
fclose(process1); // 关闭文件流
napi_create_int32(env, 0, &ret);
}
return ret;
}
更多关于ETS或者NAPI中怎么实现调用cmd命令呢(HarmonyOS 鸿蒙Next)的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
在hvigorfile.ts执行cmd命令
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
import * as fs from 'fs';
import * as path from 'path';
import { exec } from 'child_process';
export function customPluginFunction1(str?: string) {
return {
pluginId: 'CustomPluginID1',
apply(pluginContext) {
pluginContext.registerTask({
name: 'customTask1',
run: (taskContext) => {
exec('git rev-parse --short HEAD', (error, stdout, stderr) => {
if (error) {
console.error(`执行命令出错: ${error.message}`);
return;
}
console.log(`命令输出: ${stdout}`);
const filePath = path.join(__dirname, 'src/main/ets/pages/GitTestClass.ets');
console.log('filePath = ', filePath)
const newValue = '123456'
fs.readFile(filePath, 'utf8', (err, data) => {
console.log('fs.readFile')
if (err) {
console.log('读取文件时发生错误')
console.error('读取文件时发生错误:', err);
return;
}
const updatedContent = data.replace(/@State test: string = '[^']*';/g, `@State test: string = '${newValue}';`);
console.log('updatedContent = ', updatedContent)
fs.writeFile(filePath, updatedContent, 'utf8', (err) => {
if (err) {
console.error('写入文件时发生错误:', err);
return;
}
console.log('文件已更新');
});
});
});
},
dependencies: ['default@BuildJS'],
postDependencies: ['default@CompileArkTS']
})
}
}
}
export default {
system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[
customPluginFunction1()
]/* Custom plugin to extend the functionality of Hvigor. */
}
更多关于ETS或者NAPI中怎么实现调用cmd命令呢(HarmonyOS 鸿蒙Next)的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在鸿蒙Next中,ETS(Extended TypeScript)或NAPI(Native API)环境下,调用CMD命令可以通过ChildProcess
模块实现。ChildProcess
模块提供了创建子进程的能力,允许在应用中执行系统命令。
具体步骤如下:
-
导入
ChildProcess
模块:import childProcess from '[@ohos](/user/ohos).childProcess';
-
使用
exec
方法执行CMD命令:childProcess.exec('your_command_here', (error, stdout, stderr) => { if (error) { console.error(`exec error: ${error}`); return; } console.log(`stdout: ${stdout}`); console.error(`stderr: ${stderr}`); });
在代码中,your_command_here
替换为需要执行的CMD命令。exec
方法会启动一个子进程来执行该命令,并通过回调函数返回执行结果。stdout
为标准输出,stderr
为标准错误输出。
请注意,执行系统命令可能会涉及安全风险,确保命令来源可靠,避免执行恶意命令。