【问题标题】:Python subprocess throws syntax error: redirection unexpectedPython子进程抛出语法错误:重定向意外
【发布时间】:2022-01-18 10:47:51
【问题描述】:

我正在尝试运行一个 Python 脚本,该脚本将文件的位置作为 shell 命令的输入传递,然后使用 subprocess 执行该命令:

path_of_file = 'path_of_file.txt'
command = 'python3 Execute.py <<< {}'.format(path_of_file)
subprocess.run(command, shell=True)

但执行此操作会引发错误

/bin/sh: 1: Syntax error: redirection unexpected

【问题讨论】:

  • 如果不明显,您的代码会将文件名作为标准输入传递给命令。这不是明显错误,但有些不寻常。也许您实际上打算将文件名作为命令行参数?那只是subprocess.run(['python3', 'Execute.py', path_of_file])

标签: python subprocess


【解决方案1】:

除非你另外指定,subprocessshell=True 运行 sh,而不是 Bash。如果你想使用 Bash 功能,你必须明确地说出来。

path_of_file = 'path_of_file.txt'
command = 'python3 Execute.py <<< {}'.format(path_of_file)
subprocess.run(command, shell=True, executable='/bin/bash')

当然,更好的解决方法是避免 Bashism,实际上完全避免 shell=True

from shlex import split as shplit

path_of_file = 'path_of_file.txt'
command = 'python3 Execute.py'
subprocess.run(command.shplit(), input=path_of_file, text=True)

最佳实践要求您还应将 check=True 添加到 subprocess 关键字参数中,以便在子进程失败时让 Python 引发异常。

更好的是,不要将 Python 作为 Python 的子进程运行;相反,import Execute 并从那里拿走它。

也可以看看

【讨论】:

    【解决方案2】:

    它看起来像一个错字,在 bash 中输入一个文件你应该使用 &lt;&lt;&lt; 而不是 &lt;&lt;&lt;

    所以脚本应该是这样的:

    path_of_file = 'path_of_file.txt'
    command = 'python3 Execute.py << {}'.format(path_of_file)
    subprocess.run(command, shell=True)
    

    【讨论】:

    • 不,这个方法给我一个EOFError。
    • Bash 中的&lt;&lt;&lt; 功能称为“此处字符串”。它是 Bash 特有的(虽然和大多数有用的功能一样,实际上是从 ksh 借来的)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 2018-06-29
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    相关资源
    最近更新 更多