执行shell命令 [英] Execute a shell command

查看:60
本文介绍了执行shell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Rust 中执行一个 shell 命令.在 Python 中,我可以这样做:

I want to execute a shell command in Rust. In Python I can do this:

import os
cmd = r'echo "test" >> ~/test.txt'
os.system(cmd)

但 Rust 只有 std::process::Command.如何执行像 cd xxx && 这样的 shell 命令触摸 abc.txt?

But Rust only has std::process::Command. How can I execute a shell command like cd xxx && touch abc.txt?

推荐答案

你应该真的避免system.它的作用取决于正在使用的 shell 以及您使用的操作系统(您的示例几乎肯定不会在 Windows 上执行您期望的操作).

You should really avoid system. What it does depends on what shell is in use and what operating system you're on (your example almost certainly won't do what you expect on Windows).

如果您真的非常需要使用 shell 调用一些命令,您可以通过直接执行 shell(例如使用 -c 切换为 bash).

If you really, desperately need to invoke some commands with a shell, you can do marginally better by just executing the shell directly (like using the -c switch for bash).

如果由于某种原因,上述方法不可行并且您可以保证您的程序将运行在具有 shell 的系统上有问题的用户不会运行其他任何东西...

If, for some reason, the above isn't feasible and you can guarantee your program will only run on systems where the shell in question is available and users will not be running anything else...

...然后你可以使用 system 来自 libc 的调用 就像你在普通 C 中所做的那样.这算作 FFI,所以你可能想看看 std::ffi::CStr.

...then you can just use the system call from libc just as you would from regular C. This counts as FFI, so you'll probably want to look at std::ffi::CStr.

这篇关于执行shell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆