1

I'm trying to execute commands sequentially through Python.

My aim is to do something like this:

command1
calculate something
command2
...

I want the CMD to remain opened after executing 'command1' , since 'command2' is dependent on 'command1'.

I've tried these answers with no results:

This one gives me the error:

ValueError: write to closed file

while executing two communicate commands.

Python Popen - how to execute commands in nested sub shell using python

Execute Commands Sequentially in Python

Thanks in advance!

Eryk Sun
  • 33,190
  • 5
  • 92
  • 111
orohev
  • 73
  • 11
  • The only reason one might want to run multiple commands in a single shell is if the commands are dependent batch scripts that set environment variables. Otherwise use the subprocess module (`Popen` `run`, `check_output`, etc) and only use its `shell=True` argument for internal shell commands (e.g. `dir`, `copy`, etc). – Eryk Sun Aug 06 '18 at 10:31
  • Yes, the commands are dependent. – orohev Aug 06 '18 at 11:12

1 Answers1

0

I think you want this:

import os  
os.system("start cmd /k command1 & command2")  

unless you want it to quit after execting both of the commands:

import os
os.system("start cmd /c command1 & command2")

If you want to add more commands add & after command 2 and write your commands.
the first example will run both of the commands in the same window, but won't close it.

the second example will run both of the commands in the same window, and will close it afterwards

Kozova1
  • 46
  • 8
  • Thank you. I want to allow sending commands to the cmd after it is opened, for example after several Python commands to execute another command... – orohev Aug 06 '18 at 08:35
  • I'm not sure... Can I use it to execute the sequence: os.system("start cmd /k command1 & command2") x=x+1 os.system("start cmd /k command3 & command4") so that command3 and 4 will be in the same window? – orohev Aug 06 '18 at 08:49
  • I don't think so. If you can provide more of your code I might be able to help you more. – Kozova1 Aug 06 '18 at 09:05
  • I want to execute several commands, in different parts of my code. For example: I have 3 commands: vivado -mode tcl (this command opens communication with a program I use) open_hw connect_hw_server (these commands are executed by the program). I want to execute the first command and then continue with my code a bit, and after several commands in Python to execute the other 2 commands. – orohev Aug 06 '18 at 09:09
  • If you could provide more of the code, I could maybe help you to rewrite it so that it would not be needed. – Kozova1 Aug 06 '18 at 09:11
  • does [this](https://stackoverflow.com/questions/2046603/is-it-possible-to-run-function-in-a-subprocess-without-threading-or-writing-a-se) help you? – Kozova1 Aug 06 '18 at 09:13
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177475/discussion-between-orohev-and-kozova1). – orohev Aug 06 '18 at 09:17