【问题标题】:how to call a command with redirection from python如何从python调用带有重定向的命令
【发布时间】:2021-08-02 12:08:23
【问题描述】:

我可以通过以下方式成功安装(在 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 调用命令失败,而从终端运行?请帮忙!

【问题讨论】:

    标签: terminal mount python


    【解决方案1】:

    您尝试使用的 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。另见Actual meaning of shell=True in subprocess

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多