首页 > 解决方案 > 如何从python调用带有重定向的命令

问题描述

我可以通过以下方式成功安装(在 fxce4 终端中):

sshfs -o password_stdin user@example.ddnss.de:/remote/path ~/example_local_path/ <<< 'password'

但不是(在 python3 终端或 python3 脚本中):

import os
os.system("sshfs -o password_stdin user@example.ddnss.de:/remote/path ~/example_local_path/ <<< 'password'")

后者返回一个Syntax error: redirection unexpected

为什么从 python 调用命令时命令失败,而它从终端工作?请帮忙!

标签: terminalmountpython

解决方案


您尝试使用的 here-string 语法是 Bash 特定的;os.system()运行sh

subprocess无论如何,您最好还是按照os.system()文档的建议使用。

import subprocess

subprocess.check_call(
    ["sshfs", "-o", "password_stdin",
      "user@example.ddnss.de:/remote/path", 
      "~/example_local_path/"],
    input='password', text=True)

将命令拆分为令牌列表可以消除shell=True您通常希望避免的需求,尤其是在您对 shell 不太熟悉的情况下。另请参见in 的实际含义shell=Truesubprocess


推荐阅读