【问题标题】:Python Script To Run Bash command运行 Bash 命令的 Python 脚本
【发布时间】:2018-08-19 17:24:03
【问题描述】:

我正在尝试让脚本在 Bash 上运行,以将文件从本地计算机传输到网络上的远程计算机。 bash命令是 :

scp \local\path\ user@remoteip:\path\to\copy\onremote

到目前为止,这一切都很好,所以我想我会使用 python 脚本来自动化它。 这就是我想出的:

import subprocess
direct = input("Enter path to directory: ")
send = "scp " + direct + " user@remoteip:\path\to\copy\onremote"
subprocess.Popen(send)

由于某种原因,它不起作用,有什么想法吗?

【问题讨论】:

  • 我注意到的第一件事是您没有放置任何空格,因此字符串 concat 之后的命令将是 scp\local\path\user@remoteip:\path\to\copy\onremote
  • 对不起,就在那里,让我更正一下。
  • 'send' 调试器显示的值是多少?在我看来,'direct' 前后没有空格。
  • 我也会使用subprocess.callsubprocess.check_call
  • 值为:找不到文件@AlexanderChingarev

标签: python bash python-3.x


【解决方案1】:

这里的问题是 Popen() 需要一个列表。所以解决方案是将字符串拆分为空格formatted = send.split(" ")。根据有关使用 Popen() 或 call() 的问题,这里有一个很好的答案,详细说明了差异。What's the difference between subprocess Popen and call (how can I use them)?

这是对我有用的东西,使用 subprocess call()。

from subprocess import call
direct = input("Enter path to directory: ")
send = "scp" + direct + " user@remoteip:\path\to\copy\onremote"
formatted = send.split(" ")
call([formatted])

【讨论】:

  • 谢谢,但它仍然无法正常工作...让我将错误添加到问题中
  • 哦!我的错。我使用 call() 错误。所有用空格分隔的字符都需要是它自己的列表实体,我会更新我的答案
  • 谢谢!看来我的问题,以前是你的问题,是拆分字符串!美好的一天!
【解决方案2】:

建议您将参数列表传递给
subprocess.Popen(["scp", "-r", "path", ...])

但是,如果您仍想传入整个字符串,请传递一个可选的 shell 参数,例如
subprocess.Popen(send, shell=True)

【讨论】:

  • 谢谢,但这对我来说不是问题
猜你喜欢
  • 1970-01-01
  • 2013-01-21
  • 2014-10-04
  • 1970-01-01
  • 2015-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
相关资源
最近更新 更多