【问题标题】:Open shell environment and run a series of command using Python打开shell环境并使用Python运行一系列命令
【发布时间】:2020-04-20 17:25:23
【问题描述】:

似乎与Using Python to open a shell environment, run a command and exit environment 重复。我想在 Redhat 的 shell 环境中运行 ulimit 命令。过程:打开shell环境,在shell上运行ulimit命令,得到结果并退出shell environmnet。参考上面的解决方案,我试过了:

from subprocess import Popen, PIPE
def read_limit():
    p = Popen('sh', stdin=PIPE)
    file_size = p.communicate('ulimit -n')
    open_files = p.communicate('ulimit -f')
    file_locks = p.communicate('ulimit -x')
    return file_size, open_files, file_locks

但我收到错误:ValueError: I/O operation on closed file。

【问题讨论】:

    标签: python


    【解决方案1】:

    documentation for communicate() 说:

    发送数据到标准输入。从 stdout 和 stderr 读取数据,直到到达文件结尾。等待进程终止。

    之后,管道将被关闭。

    你可以使用

    p.stdin.write("something")
    p.stdin.flush()
    result = p.stdout.readline()
    

    为你的三个命令,然后

    p.stdin.close()
    p.wait()
    

    最后终止它

    【讨论】:

      猜你喜欢
      • 2014-04-05
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多