繁体   English   中英

为什么我不能从 Python 调用 SSH 终端命令?

[英]Why Can't I Call an SSH Terminal Command from Python?

我正在尝试通过 SSH 将文件复制到我的 Raspberry pi,并且我想从 python 执行 windows 终端命令,以便我以后可以自动化它。 但是,每次尝试执行它时都会出错。 SSH 命令在我手动将其放入控制台时按预期工作,但是当我从该脚本调用它时它不起作用。 我以前从未在 python 中调用过控制台命令,所以我正在尝试使用我发现的其他一些线程。 我可能做错了什么? 我还尝试运行os.system ,它没有返回错误,但也没有按应有的方式执行命令。 我正在使用 Python 3.8.1。 这是我的脚本和错误,感谢您的帮助。

代码:

import subprocess

subprocess.run(['scp <text file path> pi@<IP>:here/'])
print ("done")

错误

Traceback (most recent call last):
  File "<script file path>.py", line 3, in <module>
    subprocess.run(['scp <text file path>.txt pi@<IP>:here/'])
  File "<python file path>\Python38-32\lib\subprocess.py", line 489, in run
    with Popen(*popenargs, **kwargs) as process:
  File <python file path>\Python38-32\lib\subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File <python file path>\Python38-32\lib\subprocess.py", line 1307, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

编辑:这是我在拆分这样的一系列命令时遇到的错误:

代码:

import subprocess

subprocess.run(['scp', '<text file path>.txt', 'pi@<IP>:here/'])
print ("done")

错误:

Traceback (most recent call last):
  File "<script file path>.py", line 3, in <module>
    subprocess.run(['scp', '<text file path>.txt', 'pi@<IP>:here/'])
  File "<python file path>\Python38-32\lib\subprocess.py", line 489, in run
    with Popen(*popenargs, **kwargs) as process:
  File "<python file path>\Python38-32\lib\subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File <Python file path>\Python38-32\lib\subprocess.py", line 1307, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

当然,我放入 <> 的任何内容都是为了保护我的信息。

编辑:运行方法: 在此处输入图片说明

要么删除列表,让 shell 解析字符串

import subprocess

subprocess.run('scp <text file path> pi@<IP>:here/', shell=True)
print ("done")

或自己将您的命令拆分为其组成部分

import subprocess

subprocess.run(['scp', <text file path>, 'pi@<IP>:here/'])
print ("done")

至于您的错误,要么<text file path>是不正确的相对路径(给定当前工作目录),要么scp不在您的PATH 从错误消息中不清楚找不到哪个文件。

对于任何回到这篇文章的人来说,解决方案是使用不同的方法来运行脚本。 我正在使用似乎不喜欢它的默认 python IDLE。 尝试在计算机的控制台中运行脚本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM