简体   繁体   English

如何在顺序重要的地方在python脚本中运行多个linux命令

[英]How to run multiple linux commands in python script where order matters

I'm trying to execute several linux commands sequentially in my python script using subprocess.Popen(). 我试图使用subprocess.Popen()在我的python脚本中顺序执行几个linux命令。 However, it seems like the way I'm writing the script, python is doing some sort of execute and forget and not waiting for step 1 to finish before starting step 2. 但是,似乎我编写脚本的方式是,python正在执行某种执行和忘记操作,而不是在开始步骤2之前不等待步骤1完成。

Case in point, I'm trying to: 举例来说,我正在尝试:

  1. Execute a SQL command, which writes the results to a file in /tmp on the remote server. 执行一条SQL命令,该命令将结果写入远程服务器上/ tmp中的文件中。
  2. After I'm finished using the file, I want to delete the remote file, so we don't run out of space. 使用完文件后,我想删除远程文件,因此我们不会用完空间。

What's happening is python seems to run the cmd for step 1 and without waiting for step 1 to complete, it runs step 2. So the file is still hanging around since the delete is run before the file is created. 发生的事情是python似乎在第1步运行了cmd,并且没有等待第1步完成,而是在第2步运行。因此,由于删除操作是在创建文件之前运行的,因此该文件仍在运行。

Here's my code snippet. 这是我的代码段。 Hopefully someone can tell me how to make it so step 2 only runs after step 1 has completed. 希望有人能告诉我如何做到这一点,因此步骤2仅在步骤1完成后才能运行。 I tried to anonymize/simplify the snippet so pls excuse any mistakes made while anonymizing the code. 我试图匿名化/简化代码段,因此请原谅匿名化代码时所犯的任何错误。

   sqlCmd = "ssh " + HOST + "mysql -h host -ppwd -q select blah from table where foo = 'bar' INTO OUTFILE '/tmp/blah_bydate.csv"
   rmCmd = "ssh " + HOST + " rm -f /tmp/blah_bydate.csv"
   proc = subprocess.Popen(sqlCmd, shell=True, stdout=subprocess.PIPE)
   proc = subprocess.Popen(rmCmd, shell=True, stdout=subprocess.PIPE)

I found something on SO where the suggested solution was to do something like 我在SO上找到了一些建议的解决方案是做类似的事情

subprocess.Popen([cmd1; cmd2; cmd3], shell=True, stdout=subprocess.PIPE)

which I don't want to do since my commands are parametrized and can be long/complex. 我不想这样做,因为我的命令已参数化并且可能很长/很复杂。

只需使用subprocess.call而不是subprocess.Popen ,它就应该阻塞直到进程完成。

您可以使用proc.wait(),如果需要的话甚至可以使用超时值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM