0

I want to perform some couple of command one after one and store into variable in same shell. Whenever I try to perform next command it executes in new shell

import subprocess

cmd1 = 'cd C:\\Program Files (x86)\\openvpn\\bin\\'
output = subprocess.getoutput(cmd1) # it goes to the above directory

cmd2 = 'openvpn.exe --help'
output2 = subprocess.getoutput(cmd2) 

At the cmd2 when it runs,a new shell perform this command and tells-- 'openvpn.exe' is not recognized as an internal or external command, operable program or batch file.

I want to perform couple of commands one after another and store into variables. So I can use that variables in other commands.

3
  • The easy approach is to put all the commands into one file (tmp.cmd) and then run that file. Commented Jan 9, 2019 at 9:29
  • I want to perform couple of more commands one after another so i can store into variables and I have to use some variables in other commands. Commented Jan 9, 2019 at 9:31
  • 1
    Again, put all those commands into tmp.cmd, then run tmp.cmd from Python. The alternative is to do os.chdir() in Python instead. The horrible version of this is to use the Pexpect module and simulate input to a shell. Commented Jan 9, 2019 at 9:35

1 Answer 1

2

You should use the run method, like so:

output = subprocess.run(['openvpn.exe', '--help'], cwd='C:\\Program Files (x86)\\openvpn\\bin\\', capture_output=True)
  • cwd = current working directory (where should the command run)
  • capture_output = record the stdout, stderr streams

Then you can access your results within the stdout, stderr properties:

output.stdout  # will give you back the output of the command.

You weren't getting any results because the cd command has no effect within subprocess. It has to do with the way cd works in the first place - no process can change another processes working directory.

Sign up to request clarification or add additional context in comments.

Comments

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.