0

I'm trying to execute 10 python scripts from python code and open each of them in a new shell window.

My code :

for i in range(10):
    name_of_file = "myscript"+str(i)+".py"
    cmd = "python " + name_of_file
    os.system("gnome-terminal -e 'bash -c " + cmd + "'")

But each script file are not executing, I get only the live interpreter of python in the new terminal...

Thank you guys

2
  • I would suggest using the subprocess module, you might have more control over each one... Commented Jan 27, 2017 at 13:43
  • In addition to @fedepad I'd like to cite the documentation of os.system: "The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function." Commented Jan 27, 2017 at 13:49

2 Answers 2

1

I would suggest using the subprocess module (https://docs.python.org/2/library/subprocess.html).
In this way, you'll write something like the following:

import subprocess

cmd = ['gnome-terminal', '-x', 'bash', '-c']
for i in range(10):
    name_of_file = "myscript"+str(i)+".py"
    your_proc = subprocess.Popen(cmd + ['python %s' % (name_of_file)])
    # or if you want to use the "modern" way of formatting string you can write
    # your_proc = subprocess.Popen(cmd + ['python {}'.format(name_of_file)])
    ...

and you have more control over the processes you start.
If you want to keep using os.system(), build your command string first, then pass it to the function. In your case would be:

cmd = 'gnome-terminal -x bash -c "python {}"'.format(name_of_file)
os.system(cmd)

something along these lines.
Thanks to @anishsane for some suggestions!

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

3 Comments

Don't you think, that in the iteration 2, cmd will contain something like ['gnome-terminal', '-x', 'bash', '-c', 'python myscript0.py', 'python myscript1.py' ] instead of ['gnome-terminal', '-x', 'bash', '-c', 'python myscript1.py' ]...?
btw, with previous code, you could have used subprocess.Popen(cmd + ["python {}".format(name_of_file)])
@anishsane True, and probably is cleaner this last one that you propose...!!! I like it!
1

I think that it is to do with the string quoting of the argument to os.system. Try this:

os.system("""gnome-terminal -e 'bash -c "{}"'""".format(cmd))

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.