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 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","./"])
print pipe

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

import subprocess

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


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

How can I pass command line arguments in this case?

Asked By: Mounarajan



The command can be a string:

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

or a list:

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

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

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

It calls

perl "./ moun"

But the file “ moun” doesn’t exist.

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

Answered By: eph
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.