【发布时间】:2020-04-18 19:14:37
【问题描述】:
我正在尝试通过 SSH 将文件复制到我的 Raspberry pi,并且我想从 python 执行 windows 终端命令,以便稍后将其自动化。但是,每次尝试执行它时都会出错。当我手动将 SSH 命令放入控制台时,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
当然,我在 中输入的任何内容都是为了保护我的信息。
【问题讨论】:
-
您确定
<text file path>存在吗? -
只是拆分参数:
['scp', '<text file path>', 'pi@<IP>:here/']。现在它正在寻找具有这个长名称的可执行文件,包括空格和 args -
感谢您的快速回复。是的,我确信文件路径存在,因为将其直接复制并粘贴到命令提示符中是可行的。我尝试拆分它,但我得到了同样的错误。
-
我同意@Marat 的评论。阅读
subprocess的文档 参数通常应该分开。如果之后您有任何其他错误,请提供确切的错误消息/输出 -
当我分离参数时,我得到完全相同的错误,除了我拆分的任何参数,它们也会显示拆分。例如,在错误消息的第三行,而不是说
subprocess.run(['scp <text file path> pi@<IP>:here/'])它会说subprocess.run(['scp', '<text file path>', 'pi@<IP>:here/'])
标签: python shell ssh command-line subprocess