【问题标题】:How to use IO.popen to write-to and read-from a child process?如何使用 IO.popen 写入和读取子进程?
【发布时间】:2010-05-25 09:41:04
【问题描述】:

我正在从 ruby​​ 脚本运行 net share 以删除 Windows 网络共享。

如果共享上的文件正在使用中,net share 将询问用户是否要继续删除,因此我的脚本需要检查命令的输出,如果检测到则写出Y net share 要求它输入。

为了能够写出进程,我用访问标志"r+"打开它。

尝试使用IO#puts 写入进程时,出现错误:

Errno::EPIPE: Broken pipe

我在这里做错了什么? (错误出现在net_share.puts "Y"这一行)

net share写出的问题文本后面没有换行,所以我使用IO#readpartial读入输出。)

def delete_network_share share_path

  command = "net share #{share_path} /DELETE"

  net_share = IO.popen(command, "r+")

  text = ""
  while true

    begin
      line = net_share.readpartial 1000 #read all the input that's available
    rescue EOFError
      break
    end

    text += line

    if text.scan("Do you want to continue this operation? (Y/N)").size > 0
      net_share.puts "Y"
      net_share.flush  #probably not needed?
    end
  end
  net_share.close
end

【问题讨论】:

    标签: windows ruby popen


    【解决方案1】:

    试试 w+ 而不是 r+

      Mode |  Meaning
      -----+--------------------------------------------------------
      "r"  |  Read-only, starts at beginning of file  (default mode).
      -----+--------------------------------------------------------
      "r+" |  Read-write, starts at beginning of file.
      -----+--------------------------------------------------------
      "w"  |  Write-only, truncates existing file
           |  to zero length or creates a new file for writing.
      -----+--------------------------------------------------------
      "w+" |  Read-write, truncates existing file to zero length
           |  or creates a new file for reading and writing.
      -----+--------------------------------------------------------
      "a"  |  Write-only, starts at end of file if file exists,
           |  otherwise creates a new file for writing.
      -----+--------------------------------------------------------
      "a+" |  Read-write, starts at end of file if file exists,
           |  otherwise creates a new file for reading and
           |  writing.
    

    【讨论】:

    • 您好,我尝试了 w+(也尝试了 a+),但不幸的是遇到了同样的问题。
    【解决方案2】:

    如果您希望net share ... /delete 命令始终成功,您可以传递/y 标志:

    C:\>net share foo /delete /y
    Users have open files on foo.  Continuing the operation will force the files closed.
    
    foo was deleted successfully.
    

    【讨论】:

    • 很烦人的净共享帮助没有提到这个选项!谢谢。
    【解决方案3】:

    使用net_share.readlines 而不是开始/救援/结束。

    谷歌搜索的第二个结果ruby io.popen

    【讨论】:

    • 我不会那样做的。这将导致等待输入的应用程序出现死锁。
    猜你喜欢
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多