【问题标题】:How to call a python script on a new shell window from python code?如何从 python 代码在新的 shell 窗口上调用 python 脚本?
【发布时间】:2017-01-27 13:42:30
【问题描述】:

我正在尝试从 python 代码执行 10 个 python 脚本并在新的 shell 窗口中打开它们。

我的代码:

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 + "'")

但是每个脚本文件都没有执行,我在新终端中只得到了python的实时解释器......

谢谢大家

【问题讨论】:

  • 我建议使用 subprocess 模块,您可能对每个模块都有更多的控制权...
  • 除了@fedepad,我想引用os.system的文档:“子进程模块提供了更强大的工具来生成新进程并检索它们的结果;使用该模块比使用更可取这个函数。”

标签: python bash terminal


【解决方案1】:

我建议使用 subprocess 模块 (https://docs.python.org/2/library/subprocess.html)。
这样,您将编写如下内容:

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

您可以更好地控制您启动的流程。
如果您想继续使用os.system(),请先构建您的命令字符串,然后将其传递给函数。你的情况是:

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

类似的东西。
感谢@anishsane 的一些建议!

【讨论】:

  • 你不觉得吗,在迭代 2 中,cmd 将包含类似 ['gnome-terminal', '-x', 'bash', '-c', 'python myscript0.py', 'python myscript1.py' ] 而不是 ['gnome-terminal', '-x', 'bash', '-c', 'python myscript1.py' ]...?
  • 顺便说一句,使用以前的代码,您可以使用subprocess.Popen(cmd + ["python {}".format(name_of_file)])
  • @anishsane 是的,你建议的最后一个可能更干净......!!!我喜欢!
【解决方案2】:

我认为这与 os.system 参数的字符串引用有关。试试这个:

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

【讨论】:

    猜你喜欢
    • 2011-04-16
    • 2021-12-15
    • 2021-05-11
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 2018-03-25
    • 1970-01-01
    相关资源
    最近更新 更多