0

I have several command execution in python on Windows using subprocess.call(), but for each one I need to execute batch file with environmet setup before calling proper command, it looks like this

subprocess.call(precommand + command)

Is there way to "create" shell in python that will have batch file executed only once and in that shell command will be executed several times?

2 Answers 2

1
  1. Write commands to a bat-file (tempfile.NamedTemporaryFile())
  2. Run the bat-file (subprocess.check_call(bat_file.name))

(not tested):

#!/usr/bin/env python
from __future__ import print_function
import os
import subprocess
import tempfile

with tempfile.NamedTemporaryFile('w', suffix='.bat', delete=False) as bat_file:
    print(precommand, file=bat_file)
    print(command, file=bat_file)
rc = subprocess.call(bat_file.name)
os.remove(bat_file.name)
if rc != 0:
    raise subprocess.CalledProcessError(rc, bat_file.name)
Sign up to request clarification or add additional context in comments.

Comments

0

Do you need to get output from every command separately? If no - you can convey these commands using &&, || or ;

cd dir && cp test1 test2 && cd -

1 Comment

And here goes problem that those commands are quite long, so only 10% of them can be executed due to too long command

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.