2

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. Here's what I've tried, nothing works:

Approach 1 -- the perl script runs, but the arguments aren't passed

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

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

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

Anyone have any suggestions? Thanks!

1 Answer 1

5

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. 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

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.

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. It's also why you can't (generally) use shell syntax like ~, wildcard expansion or environment variables.

Sign up to request clarification or add additional context in comments.

8 Comments

The perl script wants the URL to be quoted, but I tried it both ways, and neither work. I've updated the question with the error that #3 generates.
I spotted a couple of other potential problems
Good catches (1) I changed the path to "../perl/bin/engine.pl" and (2) removed the []'s from the POpen command --now, it's back to executing the perl script, but still isn't passing the arguments...
I'm fairly sure you need to remove the spaces around your arguments, so addcmd = ["/usr/bin/perl", "engine.pl", "--uid", str(our_id), "--url", source_url]
Did you try without the quotes? They're only needed when running from the command line. Speaking of which, does the perl script work as expected when you run it from the command line?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.