0

I have a python code that should execute another code in some other file.

For reasons I don't have the time to explain now I need to use the subprocess-module or something similar. My fuction should use any window in which the print- commands in my second file should give their output. Here are my files:

maincode.py:

#import subprocess

def startFileInNewProcess(filename):
    proc = subprocess.Popen(["python", filename], shell=True)

startFileInNewProcess("mysecondfile.py")

mysecondfile.py:

import os
print os.getcwd()

As far as I undestood some articles on SO, the parameter shell=True should create a new window with the output of the mysecondfile.py. This does not happen! Can anybody explain why and please give improvement proposals...

monamona
  • 1,195
  • 2
  • 17
  • 43
  • I'm on a debian system, more detailed: Raspbian – monamona Nov 24 '17 at 20:13
  • No, `shell=True` doesn't create a new window. It just means that the specified command will be executed through the shell. See https://docs.python.org/3/library/subprocess.html#frequently-used-arguments – PM 2Ring Nov 24 '17 at 20:16
  • 2
    No, `shell=True` causes the first argument to be converted to a string and used as an argument to `sh -c`. You don't want `shell=True` if you are passing a list. – chepner Nov 24 '17 at 20:16
  • Here are some other helpful links, related questions [link](https://stackoverflow.com/questions/19308415/execute-terminal-command-from-python-in-new-terminal-window), [link](https://stackoverflow.com/questions/15899798/subprocess-popen-in-different-console) – Gumboy Nov 24 '17 at 20:44

2 Answers2

1

The argument shell=True will only execute the command in a shell, in the default shell in your system /bin/sh. To start a new terminal window, you need to specify the terminal:

subprocess.Popen(["xterm", "python"])

The above line opens a new xterm terminal window and executes python command in it.

GIZ
  • 4,409
  • 1
  • 24
  • 43
  • I applie your proposal to my code and got this presuming that `filename` is executable: `subprocess.Popen(["xterm", "./"+filename])` This does not wait until I pressed enter or something similar, but codes the window immediately afer end of the program... – monamona Nov 24 '17 at 20:44
0

on windows you can open a new cmd window and execute the code on that

from subprocess import Popen
from subprocess import Popen, CREATE_NEW_CONSOLE

def startFileInNewProcess(filename):
    terminal='cmd'
    command='Python'
    command=terminal +' '+ '/K' +' '+command+' '+filename
    #/K keeps the command prompt open when execution takes place
    #CREATE_NEW_CONSOLE opens a new console
    proc = subprocess.Popen(command,creationflags=CREATE_NEW_CONSOLE)
pankaj mishra
  • 2,555
  • 2
  • 17
  • 31