Skip to content Skip to sidebar Skip to footer

Multiple Shell Commands In Python (windows)

I'm working on a windows machine and I want to set a variable in the shell and want to use it with another shell command, like: set variable = abc echo %variable% I know that I co

Solution 1:

Popen can only execute one command or shell script. You can simply provide the whole shell script as single argument using ; to separate the different commands:

proc = Popen('set variable=abc;echo %variable%', shell=True)

Or you can actually just use a multiline string:

>>>from subprocess import call>>>call('''echo 1...echo 2...''', shell=True)
1
2
0

The communicate method is used to write to the stdin of the process. In your case the process immediately ends after running set variable and so the call to communicate doesn't really do anything.

You could spawn a shell and then use communicate to write the commands:

>>> proc = Popen(['sh'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
>>> proc.communicate('echo 1; echo 2\n')
('1\n2\n', '')

Note that communicate also closes the streams when it is done, so you cannot call it mulitple times. If you want an interactive session you hvae to write directly to proc.stdin and read from proc.stdout.


By the way: you can specify an env parameter to Popen so depending on the circumstances you may want to do this instead:

proc = Popen(['echo', '%variable%'], env={'variable': 'abc'})

Obviously this is going to use the echo executable and not shell built-in but it avoids using shell=True.

Post a Comment for "Multiple Shell Commands In Python (windows)"