[英]Python to call shell script with arguments
I have a shell script I need to call from a Python script.我有一个需要从 Python 脚本调用的 shell 脚本。 Only thing is that is needs to pass 7 parameters, that are basically variables, and some of those contain spaces.
唯一的问题是需要传递 7 个参数,这些参数基本上是变量,其中一些包含空格。
I see a lot of references to os.system, and to subprocess, but what about the parameters with spaces?我看到很多对 os.system 和子进程的引用,但是带有空格的参数呢? I think those will cause an issue.
我认为这些会引起问题。
Edit 2:编辑2:
subject = "Proposal"
to = "LandonStatis@stackoverflow.com"
from = "Joshua@stackoverflow.com"
REPORT_DIRECTORY = "/home/reports"
file = "/home/files/proposal.txt"
message = "Please accept me as the best answer"
#i didnt include the "flag" because i dont know the flag format
os.system('./home/scripts/send_email.pl "'+subject+'" "'+to+'" "'+from+'" "'+REPORT_DIRECTORY+'" "'+file+'" "'+message+'"')
Edit:编辑:
If you want to add a variable, you can do so like this如果你想添加一个变量,你可以这样做
os.system('ls -al '+str(x))
For example, if your username is "landon statis" with a space,例如,如果您的用户名是带有空格的“landon statis”,
you can do this: os.system('ls -al "/home/landon statis/Desktop"')
你可以这样做:
os.system('ls -al "/home/landon statis/Desktop"')
(notice the space in the command above?) (注意上面命令中的空格?)
This works for both Windows and Linux.这适用于 Windows 和 Linux。
Use double quotes to prevent word splitting.
使用双引号来防止分词。 An argument enclosed in double quotes presents itself as a single word, even if it contains whitespace separators.
用双引号括起来的参数将自身显示为一个单词,即使它包含空格分隔符。
This is the source, which is a link to Linux Documentation Project.这是源代码,它是 Linux 文档项目的链接。 Check them out, it's very useful: Advanced Bash Scripting Guide: Chapter 5 - Quoting
看看它们,它非常有用:高级 Bash 脚本指南:第 5 章 - 引用
Please do not use os.system
or subprocess
with shell=True
.请不要使用
os.system
或带有shell=True
的subprocess
进程。 Both execute a shell and are potentially vulnerable to shell injections.两者都执行一个 shell,并且可能容易受到 shell 注入的攻击。 See https://docs.python.org/3/library/subprocess.html#security-considerations for more details.
有关更多详细信息,请参阅https://docs.python.org/3/library/subprocess.html#security-considerations 。
Best way is to use subprocess
and hand it a list of arguments.最好的方法是使用
subprocess
并给它一个参数列表。 Example: Let's just use a Shell script that print its arguments.示例:让我们使用一个打印其参数的 Shell 脚本。
myscript
: myscript
:
#!/bin/sh
for arg in "$@"; do
echo "argument: $arg"
done
Then you can call this script using a list as argument:然后您可以使用列表作为参数调用此脚本:
subprocess.run(["./myscript", "first", "argument with space", "third"])
Output:输出:
argument: first
argument: argument with space
argument: third
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.