首页 > 解决方案 > How to parse a variables to subprocess.run in python

问题描述

I am new to python. I have install.py. Below are the variables stored its values. When execute/run abc.py, it's unable to copy the file from remote to local server. When samething is hardcoded values in subprocess commands, able to transfer file, but passing variable in subprocess not working. Referred other articles, but no luck.

srcuser=abcd srcip=x.x.x.x srcpath=/home/sum/mnt/ sshprkey=/home/xyz/id_rsa
subprocess.run(['sudo', 'scp', '-P22', '-i sshprkey', 'srcuser@srcip:srcpath/"mongodb-org-3.6.repo"', '/etc/yum.repos.d/'])

Thanks

标签: pythonsubprocess

解决方案


试试这个,我们将 shell 关键字参数分配给 true。

subprocess.run(['sudo', 'scp', '-P22', '-i sshprkey', 'srcuser@srcip:srcpath/"mongodb-org-3.6.repo"', '/etc/yum.repos.d/'], shell=True)

使用 Popen(从 python 文档复制) 在 Unix 上,shell=True,shell 默认为 /bin/sh。如果 args 是字符串,则该字符串指定要通过 shell 执行的命令。这意味着字符串的格式必须与在 shell 提示符下键入时的格式完全相同。这包括,例如,引用或反斜杠转义文件名,其中包含空格。如果 args 是一个序列,则第一项指定命令字符串,任何附加项将被视为 shell 本身的附加参数。

您需要确保第一项指定命令字符串

Popen(['sudo scp', '-P22', '-i sshprkey', 'srcuser@srcip:srcpath/"mongodb-org-3.6.repo"', '/etc/yum.repos.d/'],shell=True)

推荐阅读