【问题标题】:Shell to Python troublesShell 到 Python 的麻烦
【发布时间】:2011-04-13 16:49:30
【问题描述】:
    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 吗?

提前致谢。

【问题讨论】:

  • 您是否尝试使用 os.system(是的,您可以)。
  • 我可以试试 os.system 吗?我什么都没试过,因为我不知道该怎么做。
  • os.system("if !ps ax | grep -v grep | grep -v -i tmux | grep 'theserver.jar' > /dev/null; then echo '服务器启动失败! ' else echo '服务器成功启动!' fi")

标签: python shell ubuntu-10.10


【解决方案1】:

您可以使用subprocess 模块进行shell 并运行任意shell 命令,但您可能需要考虑使用PSIpsutil 模块之类的东西。

它们是非标准的,因此您必须下载并安装它们,但它们会更加健壮和抗错。 (请记住,ps 输出格式可以在不同平台之间更改)。这是一个示例 psutil 实现,它或多或少地完成了您正在尝试做的事情。如果您需要检查的不仅仅是名称,显然将'Python''theserver.jar' 交换或使用p.exep.cmdline

import psutil

def find_processes_by_name(name):
  for p in psutil.process_iter():
    try:
      if p.name == name:
        yield p.pid
    except psutil.error.AccessDenied as e:
      pass

  raise StopIteration

print "Python processes:"
for pid in find_processes_by_name('Python'):
  print '\t', pid

【讨论】:

    【解决方案2】:

    假设我想知道我是否在运行 sshd 的服务器上(只是替换示例中的 jar 文件)

    import os
    
    command=" ps ax | grep -v grep | grep -v -i tmux | grep sshd"
    
    result = os.WEXITSTATUS(os.system(command))
    
    if os.WEXITSTATUS(os.system(command)):
      print "Server failed to start!"
    else:
      print "Server successfully started!"
    

    您需要 WEXITSTATUS 来修复 os.system 调用的返回值。供您使用,只需将 sshd 替换为 theserver.jar

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-21
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-02
      • 1970-01-01
      相关资源
      最近更新 更多