Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

python 3.x - How to execute multiple command in command line with Pyhton 3.x

Thanks, everyone. I am writing a script to execute multiple command in command line. It is one part of my whole script.

I have checked many answers, but none of them solved my problem. Some of them are too old to use.

My commands are like this

cd C:/Users/Bruce/Desktop/test
set I_MPI_ROOT=C:Program FilesfiremodelsFDS6inmpi
set PATH=%I_MPI_ROOT%;%PATH%
fds_local -o 1 -p 1 test.fds
python test.py

I tried to use subprocess.run or os.system, etc. But they do not work. I don't know what happened. Here is an example I have used.

file_path = "C:/Users/Bruce/Desktop/test"
cmd1 = 'cd ' + file_path
cmd2 = "set I_MPI_ROOT=C:/Program Files/firemodels/FDS6/bin/mpi"
cmd3 = "set PATH=%I_MPI_ROOT%;%PATH%"
nMPI = '-p {}'.format(1)
nOpenMP = '-o {}'.format(1)
cmd4 = "fds_local {} {} ".format(nMPI, nOpenMP) + file_name
cmd = '{} && {} && {} && {}'.format(cmd1, cmd2, cmd3, cmd4)
subprocess.Popen(cmd, shell=True)

I am not quite familiar with subprocess. But I have worked for one week to solve this problem. It makes me crazy. Any suggestions?

question from:https://stackoverflow.com/questions/65838819/how-to-execute-multiple-command-in-command-line-with-pyhton-3-x

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

cmd needs to be a list of text, as whatever you see on shell separated by blanks. E.g. "ls -l /var/www" should be cmd=['ls','-l','/var/www']

That said, cd is better done with os.chdir. Set is better done with providing the environ dictionary into subprocess calls. Multiline is better done by putting several lines into a shell script (which can take parameters) so you do not have to mess up in python.

here is an example. If a command is not in OS's $PATH, you can fully qualify its path

from subprocess import Popen
cmd=['cd',r'C:Program Files (x86)Notepad++','&&','notepad','LICENSE','&&',r'D:ProgramToolsPutty.exe','-v']
d=Popen(cmd, shell=True)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...