Search code examples
pythonperlsubprocesspopen

Passing command line argument to subprocess module


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?


Solution

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