Use Python to generate Shell command batch execution of program code parsing

  • 2020-06-23 02:34:54
  • OfStack

This paper mainly studies Linux system using Python to generate Shell command, batch execution of the program related content, specific as follows.

These days, it is common to see similar commands executed in batches in Linux shell. For example, execute the following command:


gifsicle --delay=100 gif/App_1_hour_*_down.gif > combine_gif/App_1_hour_down.gif 
gifsicle --delay=100 gif/App_1_hour_*_up.gif > combine_gif/App_1_hour_up.gif 
gifsicle --delay=100 gif/App_2_hour_*_down.gif > combine_gif/App_2_hour_down.gif 
gifsicle --delay=100 gif/App_2_hour_*_up.gif > combine_gif/App_2_hour_up.gif 
gifsicle --delay=100 gif/App_3_hour_*_down.gif > combine_gif/App_3_hour_down.gif 
gifsicle --delay=100 gif/App_3_hour_*_up.gif > combine_gif/App_3_hour_up.gif 
gifsicle --delay=100 gif/App_4_hour_*_down.gif > combine_gif/App_4_hour_down.gif 
gifsicle --delay=100 gif/App_4_hour_*_up.gif > combine_gif/App_4_hour_up.gif 
gifsicle --delay=100 gif/App_5_hour_*_down.gif > combine_gif/App_5_hour_down.gif 

If manual input, the error rate is high, the time cost is high, the efficiency is very low. Using Shell programming is easy to batch process the above procedures, but if you are not familiar with Shell programming, it can also be easily implemented. The key is a shift in thinking. We can use Python to write the above command to a file and copy it from the file contents to #! The required Shell script file can be built from the.sh file beginning with /bin/bash. The Python code to generate the above command is as follows:


output = open("C:\\Python34\\shell_commands.txt", "w") 
 
for i in range (1, 21): 
  wr_line_1 = "gifsicle --delay=100 gif/App_" + str(i) + "_hour_*_down.gif > combine_gif/App_" + str(i) + "_hour_down.gif" + "\n" 
  wr_line_2 = "gifsicle --delay=100 gif/App_" + str(i) + "_hour_*_up.gif > combine_gif/App_" + str(i) + "_hour_up.gif" + "\n" 
  output.writelines(wr_line_1) 
  output.writelines(wr_line_2) 
output.close() 

conclusion

Above is the use of Python to generate Shell command, batch execution of the program code parsing all content, hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: