1

This is a beginner level question for anyone pro in subprocess.

In Windows, is it possible for me to send the following CMD commands using subprocesssuch that they are executed one after another in a single shell:

  1. cd C:\Users\User\myvirtualenvs\project1
  2. Scripts\activate.bat
  3. Hello.py

Effectively, I am trying to load the Virtualenv without having to manually myself touch CMD prompt.

Thanks in advance :)

1
  • 1
    I think (but I’m no cmd expert) that you separate the commands with &&. Commented Mar 24, 2018 at 3:00

1 Answer 1

2

Just like mentioned in the Comment with &&:

from subprocess import call

call(r'cd C:\ && echo 123 && dir', shell=True)

Please notice the shell=True argument.

Edit due to comment:

Shell=True is an security issue, if you're passing raw input values to the call. See this example from the docs:

from subprocess import call
filename = input("What file would you like to display?\n")
>>> What file would you like to display?
>>> non_existent; rm -rf / #
call("cat " + filename, shell=True) # Uh-oh. This will end badly...

In initially thought you want to make a small script for personal purposes. If you want to give this code away, think about packaging your code via distutils or setuptools.

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

5 Comments

"cd C:\\" <- double backslashes! Or use raw strings.
Thank you. I am planning to give this program to other users eventually and hence I would like to ask if its possible to do it without "shell=True" as I heard that it has some security issues.
Just as a side note, in the meanwhile, I did manage to do the above thingies using AutoIT :D, but yes if I can have a clean python way to do it, it would be preferrable :)
As long as you completely control the input string, it is "safe" to use shell=True. One way or another you are forced to open a subshell, in order to run your commands in sequence and have them remember the settings from activate.bat. And, as soon as you have opened a subshell, shell commands can be run from within it. Also, if you are afraid of malicious usage, it is equally dangerous to just allow the user access to cmd.exe.
As a sidenote, why are you not just making a very simple .bat file instead, doing what you want? What is the benefit of using a Python subprocess?

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.