简体   繁体   中英

How to call a python script on a new shell window from python code?

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

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))

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM