更好的远程运行Python脚本的方法

4 投票
2 回答
7364 浏览
提问于 2025-04-17 18:25

我在一台远程机器上有一个Python脚本,想从我的本地机器上执行它。这个脚本需要一些参数,如果我在那台机器上运行的话,应该是这样做的。

python python_parallel.py --num=10 --ssh=/home/user1/path/file.txt

现在,我在本地机器上有一段Python代码,用来运行上面的脚本:

from optparse import OptionParser
parser.add_option("-n", "--num", type="int", dest="num_spice",help="Enter the number")
parser.add_option("-s", "--ssh", dest="ssh_txt",help="Enter the path to the text file")
num_spice=options.num_spice
ssh_txt=options.ssh_txt

(options, args) = parser.parse_args()

os.system('ssh user1@10.100.10.201 python /home/user1/path/python_parallel.py --num=%s --ssh=%s' %(num_spice, ssh_txt) )

有没有更好的方法来做到这一点呢?我试过这个链接里的解决方案,但出现了一个错误:“ImportError: No module named ssh”。

2 个回答

2

你有没有考虑过使用 Fabric 呢?它非常简单好用。

6

我建议你看看这个plumbum模块,它可以帮助你做类似的事情。

这个模块很不错,使用起来也很简单,可以用来运行本地命令。而且你也可以很轻松地运行远程命令(通过一个上下文管理器)。

撰写回答