[Tutor] run perl script files and capture results

eryksun eryksun at gmail.com
Thu Jan 10 07:43:55 CET 2013


On Wed, Jan 9, 2013 at 8:14 PM, T. Girowall <tgirowall at yahoo.com> wrote:
>
>
> c:\scripts\perl>perl plscript.pl -cmnd1 -cmnd2
>
> cmnd1 and cmnd2 are ran on files that reside within "perl" directory.
>
> My objective:
> 1. Run the perl script using python
> 2. Capture the results from the DOS window and save it to python. Output
> consists of text names and corresponding numbers.
>
> I'm using python 2.7

subprocess.check_output returns piped stdout (optionally including
stderr) from a process

http://docs.python.org/2/library/subprocess#subprocess.check_output

universal_newlines=True replaces the Windows CRLF ('\r\n') line
endings with LF ('\n').

To set the working directory use cwd='c:/scripts/perl' (see [1]).

On Windows you can pass args as a string if you need non-standard
quoting. If you use a list instead, subprocess builds a string quoted
according to Microsoft's rules:

http://docs.python.org/2/library/subprocess#converting-argument-sequence

If the call fails check_output raises subprocess.CalledProcessError:

http://docs.python.org/2/library/subprocess#subprocess.CalledProcessError

For example:

    import subprocess

    output = subprocess.check_output(
        ['perl.exe', 'plscript.pl', '-cmnd1', '-cmnd2'],
        universal_newlines=True,
        cwd='c:/scripts/perl',
    )

Windows CreateProcess will search for 'perl.exe' on the system PATH.
For increased security you can use an absolute path such as
'C:/perl/bin/perl.exe'.

1. Using a forward slash in paths is OK for DOS/Windows system calls
(e.g. opening a file or setting the cwd of a new process), dating back
to the file system calls in MS-DOS 2.0 (1983). Otherwise a backslash
is usually required (e.g. shell commands and paths in commandline
arguments, where forward slash is typically used for options). In this
case use a raw string or os.path.join. For a raw string, note that a
trailing backslash is not allowed, e.g. r'C:\Python27\'. Instead you
could use r'C:\Python27' '\\', among other options:

http://docs.python.org/2/faq/design.html#why-can-t-raw-strings-r-strings-end-with-a-backslash


More information about the Tutor mailing list