Python:生成sudo进程(在新终端中),等待完成

2024-10-03 23:25:12 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:我的最终代码如下:

#WARNING: all " in command need to be escaped: \\"
def spawnInNewTerminal(command):
    #creates lock file
    lock = open(lockPath, 'w')
    lock.write("Currently performing task in separate terminal.")
    lock.close()

    #adds line to command to remove lock file
    command += ";rm " + lockPath

    #executes the command in a new terminal
    process = subprocess.Popen (
        ['x-terminal-emulator', '-e',  'sh -c "{0}"'.format(command) ]
        , stdout=subprocess.PIPE )
    process.wait()

    #doesn't let us proceed until the lock file has been removed by the bash command
    while os.path.exists(lockPath):
        time.sleep(0.1)

原题:

我正在编写一个简单的包装器,在最终运行LuaLaTeX之前“动态”安装任何丢失的包。它基本上是有效的,但在接近尾声时,我必须运行命令

^{pr2}$

而且,因为不能保证LaTeX编辑器允许用户输入,所以我必须调用一个新的终端来完成这项工作,这样他们就可以输入sudo密码了。在

我基本上弄明白了:要么

process = subprocess.Popen(
    shlex.split('''x-terminal-emulator -t \'Installing new packages\' -e \'sudo tlmgr install ''' + packagesString + '''\''''), stdout=subprocess.PIPE)
retcode = process.wait()

或者

os.system('''x-terminal-emulator -t \'Installing new packages\' -e \'sudo tlmgr install ''' + packagesString + '''\'''')

唯一的问题是,这行代码不会等到派生的终端进程完成。实际上,在用户输入密码或下载包之前,它会立即继续到下一行(运行实际的LuaLaTeX)!在

据我所知,这是因为sudo子进程马上就结束了。有没有办法确保tlmgr进程在继续之前完成?在


Tags: thetoinlocknew进程sudoprocess
1条回答
网友
1楼 · 发布于 2024-10-03 23:25:12

原因是x-terminal-emulator生成一个新进程并退出,因此您无法知道执行的命令何时结束。为了解决这个问题,一个解决方案是修改您的命令以添加另一个通知您的命令。因为显然x-terminal-emulator只执行一个命令,所以我们可以使用一个shell来链接它们。 可能不是最好的方法,但有一种方法是:

os.system('x-terminal-emulator -t "Installing new packages" -e "sh -c \\"sudo tlmgr install %s; touch /tmp/install_completed\\""' % packagesString)
while not os.path.exists("/tmp/install_completed"):
    time.sleep(0.1)
os.remove("/tmp/install_completed")

相关问题 更多 >