gpt4 book ai didi

python - 将命令行参数传递给子进程模块

转载 作者:行者123 更新时间:2023-12-01 04:18:04 27 4
gpt4 key购买 nike

我有一个 Python 脚本,它使用 subprocess 模块调用 Perl 脚本。在终端中,我运行 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 - 将命令行参数传递给子进程模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34079882/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com