如何等待系统命令结束 [英] How to wait for system command to end

查看:51
本文介绍了如何等待系统命令结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Ruby 中的系统命令转换 XLS 2 CSV 文件.

I'm converting an XLS 2 CSV file with a system command in Ruby.

转换后我正在处理 CSV 文件,但是当程序想要处理文件时转换仍在运行,所以当时它们不存在.

After the conversion I'm processing the CSV files, but the conversion is still running when the program wants to process the files, so at that time they are non-existent.

谁能告诉我是否可以让 Ruby 等待适当的时间让系统命令完成?

Can someone tell me if it's possible to let Ruby wait the right amount of time for the system command to finish?

现在我正在使用:

sleep 20

但如果它需要更长的时间,那当然是不对的.

but if it will take longer once, it isn't right of course.

我具体做的是:

#Call on the program to convert xls
command = "C:/Development/Tools/xls2csv/xls2csv.exe C:/TDLINK/file1.xls"
system(command)
do_stuff

def do_stuff
#This is where i use file1.csv, however, it isn't here yet
end

推荐答案

Ruby 的 system("...") 方法是同步的;即它等待它调用的命令返回退出代码,如果命令以 0 状态退出,则 system 返回 true,如果它以非 0 状态退出,则返回 false.Ruby 的反引号返回命令的输出:

Ruby's system("...") method is synchronous; i.e. it waits for the command it calls to return an exit code and system returns true if the command exited with a 0 status and false if it exited with a non-0 status. Ruby's backticks return the output of the commmand:

a = `ls`

会将 a 设置为包含当前工作目录列表的字符串.

will set a to a string with a listing of the current working directory.

所以看起来 xls2csv.exe 在完成它应该做的事情之前返回了一个退出代码.也许这是一个 Windows 问题.所以看起来你将不得不循环直到文件存在:

So it appears that xls2csv.exe is returning an exit code before it finishes what it's supposed to do. Maybe this is a Windows issue. So it looks like you're going to have to loop until the file exists:

until File.exist?("file1.csv")
  sleep 1
end

这篇关于如何等待系统命令结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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