0

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 Files\firemodels\FDS6\bin\mpi 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?

    1 Answer 1

    1

    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:\Program\Tools\Putty.exe','-v'] d=Popen(cmd, shell=True) 
    3
    • Thanks, Wang. You said that cmd should be a list. But subprocess.call("cd C:/Users/Bruce/Desktop/test && notepad", shell=True) could work and open a notepad. But when I use subprocess.call("fds test.fds", shell=True), it won't work. However, it can be executed in the command line and os.system could run normally. Why subprocess did not work while os.system do?
      – Wang
      CommentedJan 22, 2021 at 6:49
    • updated with an example for you to work with
      – Bing Wang
      CommentedJan 22, 2021 at 14:14
    • Thanks a lot, Wang. Maybe something went wrong for call and Popen in subprocess, I solved this problem with os.system. I think there must be a bug existing in subprocess module. Because same code run well with os.system.
      – Wang
      CommentedJan 24, 2021 at 5:48

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.