3

I have a Python script which calls Perl script using subprocess module. In terminal I run the Perl script like this:

perl email.pl [email protected]

I am passing in "[email protected]" as command line argument to that script. This is my Python script:

import subprocess

pipe = subprocess.Popen(["perl","./email.pl"])
print pipe

This works fine. But if I pass arguments it throws file not found:

import subprocess

pipe = subprocess.Popen(["perl","./email.pl moun"])
print pipe

Error:

<subprocess.Popen object at 0x7ff7854d6550>
Can't open perl script "./email.pl moun": No such file or directory

How can I pass command line arguments in this case?

0

1 Answer 1

4

The command can be a string:

pipe = subprocess.Popen("perl ./email.pl moun")

or a list:

pipe = subprocess.Popen(["perl", "./email.pl", "moun"])

When it is a list, Python will escape special chars. So when you say

pipe = subprocess.Popen(["perl","./email.pl moun"])

It calls

perl "./email.pl moun"

But the file "email.pl moun" doesn't exist.

Above is a rough explanation and only works in Windows. For more detail, see @ShadowRanger 's comment.

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

1 Comment

The solution (second block of code) is correct, but the explanation is only loosely applicable to Windows systems, and wrong everywhere else. On non-Windows systems, Python isn't escaping a thing in the list based invocation (it's converting to a C level array of C-style strings and passing it directly to an execvp system call after fork). The first block of code isn't legal without passing shell=True on non-Windows systems. Even on Windows systems, the list based invocation is usually safer, because Python is better at handling the necessary escaping to produce the command string.

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.