Shell 到 Python 的麻烦
if ! ps ax | grep -v grep | grep -v -i tmux | grep "theserver.jar" > /dev/null; then
echo "Server failed to start!"
else
echo "Server successfully started!"
fi
请问我怎样才能用 python 做到这一点? 我不知道该怎么做。请帮忙:( 我可以使用 os.system 吗?
提前致谢。
if ! ps ax | grep -v grep | grep -v -i tmux | grep "theserver.jar" > /dev/null; then
echo "Server failed to start!"
else
echo "Server successfully started!"
fi
How can i make this with python, please?
I can't figure out how to do it. Please, help :(
Can i use os.system?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 subprocess 模块进行 shell 并运行任意 shell 命令,但您可能想要考虑使用 PSI 或 psutil 模块。
它们是非标准的,因此您必须下载并安装它们,但它们会更加健壮并且不易出错。 (请记住,
ps
输出格式可能会在不同平台上发生变化)。这是一个示例 psutil 实现,它或多或少可以完成您想要做的事情。显然,如果您需要将'Python'
替换为'theserver.jar'
或使用p.exe
或p.cmdline
需要检查的不仅仅是名称。You can shell out with the subprocess module and run arbitrary shell commands, but you may want to consider using something like the PSI or psutil modules.
They are non-standard so you will have to download and install them, but they will be much more robust and resistant to errors. (Remember that
ps
output formats can change across different platforms). Here is an example psutil implementation that does more or less what you're trying to do. Obviously swap'Python'
with'theserver.jar'
or usep.exe
orp.cmdline
if you need to inspect more than just the name.假设我想知道我是否在运行 sshd 的服务器上(只是示例中 jar 文件的替换),
您需要 WEXITSTATUS 来修复 os.system 调用的返回值。供您使用,只需将 sshd 替换为 theserver.jar
Say I want to find out if I am on a server running sshd(just a replacement for the jar file in your example)
You need the WEXITSTATUS to fix the return value from the os.system call. For your use just replace sshd with theserver.jar