简体   繁体   English

无法使用python将参数传递给perl脚本

[英]Cant pass arguments to perl script using python

I'm trying to do what should be a simple action-- execute a perl script from within a python3 script, passing several arguments to the perl script. 我正在尝试做一个简单的动作-从python3脚本中执行一个perl脚本,将几个参数传递给perl脚本。 Here's what I've tried, nothing works: 这是我尝试过的,没有任何效果:

Approach 1 -- the perl script runs, but the arguments aren't passed 方法1-运行perl脚本,但不传递参数

addexec = "../perl/bin/engine.pl"
addvars = " --uid " + str(our_id) + " --url '" + source_url + "'"
addtodb = subprocess.Popen(["/usr/bin/perl", addexec, addvars])

Approach 2 -- the perl script doesn't run, says file not found 方法2-Perl脚本未运行,表示未找到文件

addexec = "../perl/bin/engine.pl --uid " + str(our_id) + " --url '" + source_url
addtodb = subprocess.Popen(["/usr/bin/perl", addexec])

Approach 3 -- the perl script doesn't run, generates errors 方法3-Perl脚本无法运行,会产生错误

addcmd = ["/usr/bin/perl", "../perl/bin/engine.pl", " --uid ", str(our_id), " --url '", source_url, "'"]
addtodb = subprocess.Popen(addcmd)

Anyone have any suggestions? 有人有什么建议吗? Thanks! 谢谢!

Approach 3 looks broadly correct, but you almost certainly don't want to "quote" the URL, need to provide the correct script path, and want to pass a single list to Popen . 方法3大致上是正确的,但是您几乎可以肯定不想“引用” URL,需要提供正确的脚本路径,并希望将单个列表传递给Popen Try: 尝试:

addcmd = ["/usr/bin/perl", "../perl/bin/engine.pl", "--uid", str(our_id), "--url", source_url]
addtodb = subprocess.Popen(addcmd)

Update: incorporated fix from @AJefferiss 更新:来自@AJefferiss的合并修复

There seems to be an underlying misconception here around how program arguments are handled. 围绕程序参数的处理方式似乎存在潜在的误解。

A command shell determines program arguments by parsing user input -- typically splitting on spaces (except where enclosed in quotes). 命令外壳通过解析用户输入来确定程序参数-通常在空格上分割(用引号引起的除外)。 In contrast, the underlying APIs like Popen accept a list of arguments directly. 相反,诸如Popen之类的基础API直接接受参数列表。

The upshot is that when using such APIs 1) you don't need the quotes, and 2) you need to drop extra spaces around arguments. 结果是,使用此类API时,1)不需要引号,2)需要在参数周围添加多余的空格。 It's also why you can't (generally) use shell syntax like ~ , wildcard expansion or environment variables. 这也是为什么您不能(通常)使用诸如~ ,通配符扩展或环境变量之类的shell语法的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM