terminal - 如何从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 调用命令时命令失败,而它从终端工作?请帮忙!
解决方案
您尝试使用的 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=True
subprocess
推荐阅读
- javascript - 如何使用广告牌js做饼图加载动画
- javascript - 如何在 Vuejs 中从子级向父级 $emit 以重置数据列表
- javascript - 如何使用 javascript setinterval 方法定期刷新剑道网格
- python - Scrapy:如何在单独的函数中加载多个项目?
- python - 如何暂停 python 的 for 循环,直到 Arduino 响应
- xml - cvc-elt.1:找不到元素“hazelcast”的声明
- pdf - ps2pdf - 无法打开初始设备
- java - android SDK 源代码在哪里创建了 protobuf 编码的 AndroidManifest.xml 文件?
- c# - 如何在不添加额外 \ 参数的情况下传递加密密码?
- php - 如何识别和删除所有未分配给任何帖子/自定义帖子/页面以及重复的图像/pdf