Bash脚本不会与Python中的子进程一起运行

2024-03-28 19:43:20 发布

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

出于某种原因,无论我尝试了多少变体,我似乎都无法执行我编写的bash脚本。这个命令在终端中是100%正常的,但是当我尝试用子进程调用它时,它什么也不返回。在

from os import listdir
import subprocess

computer_name = 'homedirectoryname'

moviefolder = '/Users/{}/Documents/Programming/Voicer/Movies'.format(computer_name)

string = 'The lion king'

for i in listdir(moviefolder):
    title = i.split('.')
    formatted_title = title[0].replace(' ', '\ ')

    if string.lower() == title[0].lower():
        command = 'vlc {}/{}.{}'.format(moviefolder, formatted_title, title[1])

        subprocess.call(["/usr/local/bin",'-i','-c', command], stdout=subprocess.PIPE,
                                                        stderr=subprocess.PIPE, shell=True)
    else:
        continue

bash可执行文件如下所示:

^{pr2}$

我哪里出错了?在


Tags: nameimportbashformatstringtitle变体lower
3条回答

由于您使用的是shell=True,因此命令必须是字符串:

On Unix with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. (docs)

就像您在注释中提到的,当您正确地从shell捕获错误(并取出错误的^{cd2>};或者相应地重构适合此用法的命令行,即传递字符串而不是列表时,您会得到^{cd1>})。

为了说明这一点,您正试图使用一些选项运行命令^{cd3>};但是,这当然不是一个有效的命令,因此失败。

您似乎要运行的实际脚本将声明一个函数,然后退出,这将导致函数定义再次丢失,因为运行执行此函数声明的shell的子进程现在终止并将其所有资源释放回系统。

也许你应该后退几步,解释你真正想要完成的事情,但实际上,这应该是一个新的、独立的问题。

假设您实际上正在运行^{cd4>},并且猜测其他一些事情,也许您确实想要

subprocess.call(['vlc','{}/{}.{}'.format(moviefolder, formatted_title, title[1]),
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)

如果您的^{cd5>}正确,则不需要显式指定^{{cd6>}(如果您的^{cd5>}错误,请在前面的代码中更正它,而不是为要调用的可执行文件硬编码目录)。

您应该直接调用open

import os
import subprocess

computer_name = 'homedirectoryname'

moviefolder = '/Users/{}/Documents/Programming/Voicer/Movies'.format(computer_name)

string = 'The lion king'

for filename in os.listdir(moviefolder):
    title = filename.split('.')

    if string.lower() == title[0].lower():
        subprocess.call(['open', '-a', '/Applications/VLC.app/Contents/MacOS/VLC', os.path.join(moviefolder, filename)])

相关问题 更多 >