【问题标题】:Terminal command through python hanging after opening program打开程序后通过python挂起的终端命令
【发布时间】:2020-02-04 03:27:08
【问题描述】:

我正在使用 python 使用它的命令启动一个程序,但是在执行命令后,脚本会卡住,只有在我关闭已打开的窗口时才会继续。 所以,如果我做一些非常简单的事情:

    import os
    os.system('gedit')
    print('aaaaaaaaaaaaa')

在我关闭文本编辑器之前它不会打印。 subprocess.call 也是如此

【问题讨论】:

  • 它不会被绞死。它以正确的方式进行。您使用os.system('gedit') 打开了编辑器。您没有通过任何关闭命令。所以它坚持在那里
  • 但是不关窗我怎么继续前进呢?
  • 更改这行代码os.system('gedit &')。它将在后台运行。您可以继续编写代码。

标签: python subprocess os.system


【解决方案1】:

我已经编写了一个工作代码,可以满足您的需求。

我已经在 RedHat 7 Linux 上对其进行了测试,它按预期工作。

代码:

import subprocess

proc = subprocess.Popen(["gedit"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
print("STDOUT: {0} \nSTDERR: {1}".format(stdout, stderr))
print("After I closed Gedit")

输出:

>>> python3 test.py 
STDOUT: b'' 
STDERR: b'\n(gedit:683047): GVFS-RemoteVolumeMonitor-WARNING **: 08:20:31.346: remote volume monitor with dbus name org.gtk.vfs.GoaVolumeMonitor is not supported\n'
After I closed Gedit

注意:当然,Gedit 已经打开,当我关闭它时,程序继续运行。

【讨论】:

    猜你喜欢
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 2017-06-17
    • 2012-11-21
    相关资源
    最近更新 更多