我正在编写一个将参数传递给 shell 脚本的 python 程序。
这是我的 python 代码:
import subprocess
Process=subprocess.Popen('./copyImage.sh %s' %s str(myPic.jpg))
还有我的“copyImage.sh”:
#!/bin/sh
cp /home/pi/project/$1 /home/pi/project/newImage.jpg
我可以毫无问题地在终端上运行脚本。但是执行python代码时,终端返回"NameError: name 'myPic' is not defined"
。
如果我将语法更改为
Process=subprocess.Popen('./copyImage.sh %s' %s "myPic.jpg")
然后终端返回"OSError: [Errno 2] No such file or directory"
。
我关注了这个:Python: executing shell script with arguments(variable), but argument is not read in shell script但它没有帮助。
最佳答案
subprocess
模块需要参数列表,而不是空格分隔的字符串。你尝试的方式导致 python 寻找一个名为 "copyImage.sh myPic.jpg"
的程序并在没有参数的情况下调用它,而你想寻找一个名为 copyImage.sh
并用一个参数调用它。
subprocess.check_call(['copyImage.sh', 'myPic.jpg'])
我还想提一下,由于您的脚本只是在 shell 中调用复制,您可能应该去掉中间人并只使用 python 的 shutil.copy
直接地。它是比为此任务运行子流程更合适的工具。
关于python - 从 Python 向 shell 脚本传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34279080/