简体   繁体   English

如何从python代码在新的shell窗口上调用python脚本?

[英]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. 我正在尝试从python代码执行10个python脚本,并在一个新的shell窗口中打开每个脚本。

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... 但是每个脚本文件都没有执行,我在新终端中仅获得python的实时解释器...

Thank you guys 感谢大伙们

I think that it is to do with the string quoting of the argument to os.system. 我认为这与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 ). 我建议使用subprocess模块( 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. 如果要继续使用os.system() ,请首先构建命令字符串,然后将其传递给函数。 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! 感谢@anishsane提供一些建议!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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