将命令行参数传递给子进程模块
Passing command line argument to subprocess module
我有一个 python 脚本,它使用子进程模块调用 perl 脚本。
在终端 i 运行 这样的 perl 脚本
perl email.pl raj@gmail.com
我将 raj@email.com 作为命令行参数传递给该脚本
这是我的Python脚本
import subprocess
pipe = subprocess.Popen(["perl","./email.pl"])
print pipe
这个很好用
但是如果我传递参数它会抛出找不到文件
import subprocess
pipe = subprocess.Popen(["perl","./email.pl moun"])
print pipe
错误:
<subprocess.Popen object at 0x7ff7854d6550>
Can't open perl script "./email.pl moun": No such file or directory
在这种情况下我如何传递命令行参数?
命令可以是字符串:
pipe = subprocess.Popen("perl ./email.pl moun")
或列表:
pipe = subprocess.Popen(["perl", "./email.pl", "moun"])
当它是一个列表时,Python 将转义特殊字符。所以当你说
pipe = subprocess.Popen(["perl","./email.pl moun"])
它调用
perl "./email.pl moun"
但是文件 "email.pl moun" 不存在。
以上是粗略的解释,仅适用于Windows。更多详细信息,请参阅@ShadowRanger 的评论。
我有一个 python 脚本,它使用子进程模块调用 perl 脚本。
在终端 i 运行 这样的 perl 脚本
perl email.pl raj@gmail.com
我将 raj@email.com 作为命令行参数传递给该脚本
这是我的Python脚本
import subprocess
pipe = subprocess.Popen(["perl","./email.pl"])
print pipe
这个很好用
但是如果我传递参数它会抛出找不到文件
import subprocess
pipe = subprocess.Popen(["perl","./email.pl moun"])
print pipe
错误:
<subprocess.Popen object at 0x7ff7854d6550>
Can't open perl script "./email.pl moun": No such file or directory
在这种情况下我如何传递命令行参数?
命令可以是字符串:
pipe = subprocess.Popen("perl ./email.pl moun")
或列表:
pipe = subprocess.Popen(["perl", "./email.pl", "moun"])
当它是一个列表时,Python 将转义特殊字符。所以当你说
pipe = subprocess.Popen(["perl","./email.pl moun"])
它调用
perl "./email.pl moun"
但是文件 "email.pl moun" 不存在。
以上是粗略的解释,仅适用于Windows。更多详细信息,请参阅@ShadowRanger 的评论。