简体   繁体   中英

Using Python to Automate Command Line Program with INIT file and Feed Commands to It

I am fairly new to programming so apologies in advance if my terminology isnt great here.

I am looking to automate a program which I normally run through the command line. When running it through the command window, I first need to load an "INIT" file, then navigate to the directory, then enter code to run the correct input file with the relevant MPI settings. So typically the command window instructions would be:

  1. fdsinit - the program is called "FDS" and this command allows the command window to run FDS files.
  2. change directory to where the input file is stored.
  3. fds_local -p 2 -o 2 1.fds - fds_local being the command which runs FDS, -p 2 -o 2 being the information for the MPI and 1.fds being the input file.

I first tried to using OS to acheive this. However, using the os.system(cmd) function doesn't seem to allow you to open the init file then input commands into the same command window instance afterwards so based on previous responses on here I determined that the subprocess module would work best.

I got as far as this as this with a lot of reading on here...

import os
from subprocess import Popen, PIPE

# changes directory to directory where input file is saved.

base = (os.getcwd())
string = f"{base}/4"
os.chdir(string)

# runs the program

cmd = 'cmd.exe fdsinit'

p = Popen(cmd, stdin=PIPE , stdout=PIPE, bufsize=0, shell=True)

p.stdin.write(b"fds_local -p 2 -o 2 1.fds\n")
p.stdin.close()
p.wait()

This code runs without error but doesnt perform the desired function, ie running the program with the input file.

Does anyone have any advice?

Thanks in advance,

... Managed to work this out myself.

For the record, the issue was trying to open the init file and cmd.exe at the same time. So the solution is below should anyone be trying to do the same think with Fire Dynamics Simulator or a similar running program.

import os
from subprocess import Popen, PIPE

# changes directory to directory where input file is saved.

base = (os.getcwd())
string = f"{base}/4"
os.chdir(string)

cmd = 'cmd.exe'

p = Popen(cmd, stdin=PIPE , stdout=PIPE, bufsize=0, shell=True)

p.stdin.write(b"fdsinit\*desired folder name*")
p.stdin.write(b"fds_local -p 2 -o 2 *filename*.fds\n")
p.stdin.close()
p.wait();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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