简体   繁体   English

如何在远程主机上运行本地python脚本并使用子进程与之通信?

[英]How can I run a local python script on a remote host and communicate with it using subprocess?

I'm trying to write a Python program that executes a local Python script on a remote host and lets me communicate with the script when it's running. 我正在尝试编写一个Python程序,该程序在远程主机上执行本地 Python脚本,并让我在脚本运行时与其通信。

My code currently consists of the two files run.py and remote.py : 我的代码当前包含两个文件run.pyremote.py

run.py : run.py

import os
import subprocess as sp

with open(os.path.join(os.path.dirname(__file__), "remote.py")) as scriptf:
    node_script = scriptf.read()

sess = sp.Popen(["ssh", "remote_host", "/usr/bin/python -"], stdin=sp.PIPE, stdout=sp.PIPE)
stdout, stderr = sess.communicate(node_script)
print(stdout, stderr)
sess.stdin.write("Print me this!\n")

remote.py : remote.py

import sys

print("Hello!")

while True:
    line = input()
    print(line)

This gives me the following error: 这给了我以下错误:

$ python run.py
Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
EOFError: EOF when reading a line
('Hello!\n', None)
Traceback (most recent call last):
  File "run.py", line 10, in <module>
    sess.stdin.write("Print me this!\n")
ValueError: I/O operation on closed file

Is there any way I can pipe a python script into a remote Python interpreter like this AND be able to use something like input() on that script later? 有什么办法可以将python脚本通过这种方式传递到远程Python解释器中,并且以后可以在该脚本上使用诸如input()类的东西吗? How could I change my example to work? 我该如何改变自己的榜样呢?

您可以尝试使用paramiko-sftp 链接将python脚本传输到远程系统,然后使用paramiko-ssh 链接登录到远程系统以在远程系统上运行脚本。

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

相关问题 如何在远程Spark集群上运行本地Python脚本? - How do I run a local Python script on a remote Spark cluster? 如何使用挂载的文件系统在远程服务器上使用本地库运行子进程? - How do I run a subprocess using local librairies on a remote server using mounted file systems? 如何在远程机器上运行本地python脚本 - how to run local python script on remote machine 在远程主机上运行带有 args 的本地 python 脚本 - Running a local python script with args on a remote host 如何使用我的本地python安装在远程服务器上运行本地脚本? - How to run a local script on a remote server using my local python installation? 如何终止使用 python 子进程启动的远程进程? - How can I terminate a remote process that I launched with a python subprocess? 在远程linux主机上运行带有参数的python脚本 - run python script with arguments on a remote linux host 如何使用 Python 与 Websocket 通信 - How can I communicate with the Websocket using Python 如何使用子进程模块从python脚本运行AVL(二进制)? - How do I run AVL (a binary) from a python script using the subprocess module? 如何使用另一个交付中的子进程运行python脚本 - How to run python script using subprocess from another delivery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM