mirror of
https://github.com/python/cpython.git
synced 2024-11-26 11:24:40 +08:00
Added Peter Astrand's subprocess module.
This commit is contained in:
parent
abf8a56e68
commit
5b3687df2e
1141
Lib/subprocess.py
Normal file
1141
Lib/subprocess.py
Normal file
File diff suppressed because it is too large
Load Diff
2
Lib/test/output/test_subprocess
Normal file
2
Lib/test/output/test_subprocess
Normal file
@ -0,0 +1,2 @@
|
||||
test_subprocess
|
||||
.........
|
514
Lib/test/test_subprocess.py
Normal file
514
Lib/test/test_subprocess.py
Normal file
@ -0,0 +1,514 @@
|
||||
import unittest
|
||||
from test import test_support
|
||||
import subprocess
|
||||
import sys
|
||||
import signal
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
mswindows = (sys.platform == "win32")
|
||||
|
||||
#
|
||||
# Depends on the following external programs: Python
|
||||
#
|
||||
|
||||
if mswindows:
|
||||
SETBINARY = 'import msvcrt; msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY);'
|
||||
else:
|
||||
SETBINARY = ''
|
||||
|
||||
class ProcessTestCase(unittest.TestCase):
|
||||
def mkstemp(self):
|
||||
"""wrapper for mkstemp, calling mktemp if mkstemp is not available"""
|
||||
if hasattr(tempfile, "mkstemp"):
|
||||
return tempfile.mkstemp()
|
||||
else:
|
||||
fname = tempfile.mktemp()
|
||||
return os.open(fname, os.O_RDWR|os.O_CREAT), fname
|
||||
|
||||
#
|
||||
# Generic tests
|
||||
#
|
||||
def test_call_seq(self):
|
||||
"""call() function with sequence argument"""
|
||||
rc = subprocess.call([sys.executable, "-c", "import sys; sys.exit(47)"])
|
||||
self.assertEqual(rc, 47)
|
||||
|
||||
def test_call_kwargs(self):
|
||||
"""call() function with keyword args"""
|
||||
newenv = os.environ.copy()
|
||||
newenv["FRUIT"] = "banana"
|
||||
rc = subprocess.call([sys.executable, "-c",
|
||||
'import sys, os;' \
|
||||
'sys.exit(os.getenv("FRUIT")=="banana")'],
|
||||
env=newenv)
|
||||
self.assertEqual(rc, 1)
|
||||
|
||||
def test_stdin_none(self):
|
||||
""".stdin is None when not redirected"""
|
||||
p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
p.wait()
|
||||
self.assertEqual(p.stdin, None)
|
||||
|
||||
def test_stdout_none(self):
|
||||
""".stdout is None when not redirected"""
|
||||
p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
|
||||
stdin=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
p.wait()
|
||||
self.assertEqual(p.stdout, None)
|
||||
|
||||
def test_stderr_none(self):
|
||||
""".stderr is None when not redirected"""
|
||||
p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
|
||||
p.wait()
|
||||
self.assertEqual(p.stderr, None)
|
||||
|
||||
def test_executable(self):
|
||||
"""executable"""
|
||||
p = subprocess.Popen(["somethingyoudonthave", "-c", "import sys; sys.exit(47)"],
|
||||
executable=sys.executable)
|
||||
p.wait()
|
||||
self.assertEqual(p.returncode, 47)
|
||||
|
||||
def test_stdin_pipe(self):
|
||||
"""stdin redirection"""
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys; sys.exit(sys.stdin.read() == "pear")'],
|
||||
stdin=subprocess.PIPE)
|
||||
p.stdin.write("pear")
|
||||
p.stdin.close()
|
||||
p.wait()
|
||||
self.assertEqual(p.returncode, 1)
|
||||
|
||||
def test_stdin_filedes(self):
|
||||
"""stdin is set to open file descriptor"""
|
||||
tf = tempfile.TemporaryFile()
|
||||
d = tf.fileno()
|
||||
os.write(d, "pear")
|
||||
os.lseek(d, 0, 0)
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys; sys.exit(sys.stdin.read() == "pear")'],
|
||||
stdin=d)
|
||||
p.wait()
|
||||
self.assertEqual(p.returncode, 1)
|
||||
|
||||
def test_stdin_fileobj(self):
|
||||
"""stdin is set to open file object"""
|
||||
tf = tempfile.TemporaryFile()
|
||||
tf.write("pear")
|
||||
tf.seek(0)
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys; sys.exit(sys.stdin.read() == "pear")'],
|
||||
stdin=tf)
|
||||
p.wait()
|
||||
self.assertEqual(p.returncode, 1)
|
||||
|
||||
def test_stdout_pipe(self):
|
||||
"""stdout redirection"""
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys; sys.stdout.write("orange")'],
|
||||
stdout=subprocess.PIPE)
|
||||
self.assertEqual(p.stdout.read(), "orange")
|
||||
|
||||
def test_stdout_filedes(self):
|
||||
"""stdout is set to open file descriptor"""
|
||||
tf = tempfile.TemporaryFile()
|
||||
d = tf.fileno()
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys; sys.stdout.write("orange")'],
|
||||
stdout=d)
|
||||
p.wait()
|
||||
os.lseek(d, 0, 0)
|
||||
self.assertEqual(os.read(d, 1024), "orange")
|
||||
|
||||
def test_stdout_fileobj(self):
|
||||
"""stdout is set to open file object"""
|
||||
tf = tempfile.TemporaryFile()
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys; sys.stdout.write("orange")'],
|
||||
stdout=tf)
|
||||
p.wait()
|
||||
tf.seek(0)
|
||||
self.assertEqual(tf.read(), "orange")
|
||||
|
||||
def test_stderr_pipe(self):
|
||||
"""stderr redirection"""
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys; sys.stderr.write("strawberry")'],
|
||||
stderr=subprocess.PIPE)
|
||||
self.assertEqual(p.stderr.read(), "strawberry")
|
||||
|
||||
def test_stderr_filedes(self):
|
||||
"""stderr is set to open file descriptor"""
|
||||
tf = tempfile.TemporaryFile()
|
||||
d = tf.fileno()
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys; sys.stderr.write("strawberry")'],
|
||||
stderr=d)
|
||||
p.wait()
|
||||
os.lseek(d, 0, 0)
|
||||
self.assertEqual(os.read(d, 1024), "strawberry")
|
||||
|
||||
def test_stderr_fileobj(self):
|
||||
"""stderr is set to open file object"""
|
||||
tf = tempfile.TemporaryFile()
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys; sys.stderr.write("strawberry")'],
|
||||
stderr=tf)
|
||||
p.wait()
|
||||
tf.seek(0)
|
||||
self.assertEqual(tf.read(), "strawberry")
|
||||
|
||||
def test_stdout_stderr_pipe(self):
|
||||
"""capture stdout and stderr to the same pipe"""
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys;' \
|
||||
'sys.stdout.write("apple");' \
|
||||
'sys.stdout.flush();' \
|
||||
'sys.stderr.write("orange")'],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT)
|
||||
self.assertEqual(p.stdout.read(), "appleorange")
|
||||
|
||||
def test_stdout_stderr_file(self):
|
||||
"""capture stdout and stderr to the same open file"""
|
||||
tf = tempfile.TemporaryFile()
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys;' \
|
||||
'sys.stdout.write("apple");' \
|
||||
'sys.stdout.flush();' \
|
||||
'sys.stderr.write("orange")'],
|
||||
stdout=tf,
|
||||
stderr=tf)
|
||||
p.wait()
|
||||
tf.seek(0)
|
||||
self.assertEqual(tf.read(), "appleorange")
|
||||
|
||||
def test_cwd(self):
|
||||
"""cwd"""
|
||||
tmpdir = os.getenv("TEMP", "/tmp")
|
||||
tmpdir = os.path.realpath(tmpdir)
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys,os;' \
|
||||
'sys.stdout.write(os.getcwd())'],
|
||||
stdout=subprocess.PIPE,
|
||||
cwd=tmpdir)
|
||||
self.assertEqual(p.stdout.read(), tmpdir)
|
||||
|
||||
def test_env(self):
|
||||
"""env"""
|
||||
newenv = os.environ.copy()
|
||||
newenv["FRUIT"] = "orange"
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys,os;' \
|
||||
'sys.stdout.write(os.getenv("FRUIT"))'],
|
||||
stdout=subprocess.PIPE,
|
||||
env=newenv)
|
||||
self.assertEqual(p.stdout.read(), "orange")
|
||||
|
||||
def test_communicate(self):
|
||||
"""communicate()"""
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys,os;' \
|
||||
'sys.stderr.write("pineapple");' \
|
||||
'sys.stdout.write(sys.stdin.read())'],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
(stdout, stderr) = p.communicate("banana")
|
||||
self.assertEqual(stdout, "banana")
|
||||
self.assertEqual(stderr, "pineapple")
|
||||
|
||||
def test_communicate_returns(self):
|
||||
"""communicate() should return None if no redirection is active"""
|
||||
p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(47)"])
|
||||
(stdout, stderr) = p.communicate()
|
||||
self.assertEqual(stdout, None)
|
||||
self.assertEqual(stderr, None)
|
||||
|
||||
def test_communicate_pipe_buf(self):
|
||||
"""communicate() with writes larger than pipe_buf"""
|
||||
# This test will probably deadlock rather than fail, if
|
||||
# communicate() does not work properly.
|
||||
x, y = os.pipe()
|
||||
if mswindows:
|
||||
pipe_buf = 512
|
||||
else:
|
||||
pipe_buf = os.fpathconf(x, "PC_PIPE_BUF")
|
||||
os.close(x)
|
||||
os.close(y)
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys,os;'
|
||||
'sys.stdout.write(sys.stdin.read(47));' \
|
||||
'sys.stderr.write("xyz"*%d);' \
|
||||
'sys.stdout.write(sys.stdin.read())' % pipe_buf],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
string_to_write = "abc"*pipe_buf
|
||||
(stdout, stderr) = p.communicate(string_to_write)
|
||||
self.assertEqual(stdout, string_to_write)
|
||||
|
||||
def test_writes_before_communicate(self):
|
||||
"""stdin.write before communicate()"""
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys,os;' \
|
||||
'sys.stdout.write(sys.stdin.read())'],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
p.stdin.write("banana")
|
||||
(stdout, stderr) = p.communicate("split")
|
||||
self.assertEqual(stdout, "bananasplit")
|
||||
self.assertEqual(stderr, "")
|
||||
|
||||
def test_universal_newlines(self):
|
||||
"""universal newlines"""
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys,os;' + SETBINARY + \
|
||||
'sys.stdout.write("line1\\n");' \
|
||||
'sys.stdout.flush();' \
|
||||
'sys.stdout.write("line2\\r");' \
|
||||
'sys.stdout.flush();' \
|
||||
'sys.stdout.write("line3\\r\\n");' \
|
||||
'sys.stdout.flush();' \
|
||||
'sys.stdout.write("line4\\r");' \
|
||||
'sys.stdout.flush();' \
|
||||
'sys.stdout.write("\\nline5");'
|
||||
'sys.stdout.flush();' \
|
||||
'sys.stdout.write("\\nline6");'],
|
||||
stdout=subprocess.PIPE,
|
||||
universal_newlines=1)
|
||||
stdout = p.stdout.read()
|
||||
if hasattr(open, 'newlines'):
|
||||
# Interpreter with universal newline support
|
||||
self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
|
||||
else:
|
||||
# Interpreter without universal newline support
|
||||
self.assertEqual(stdout, "line1\nline2\rline3\r\nline4\r\nline5\nline6")
|
||||
|
||||
def test_universal_newlines_communicate(self):
|
||||
"""universal newlines through communicate()"""
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys,os;' + SETBINARY + \
|
||||
'sys.stdout.write("line1\\n");' \
|
||||
'sys.stdout.flush();' \
|
||||
'sys.stdout.write("line2\\r");' \
|
||||
'sys.stdout.flush();' \
|
||||
'sys.stdout.write("line3\\r\\n");' \
|
||||
'sys.stdout.flush();' \
|
||||
'sys.stdout.write("line4\\r");' \
|
||||
'sys.stdout.flush();' \
|
||||
'sys.stdout.write("\\nline5");'
|
||||
'sys.stdout.flush();' \
|
||||
'sys.stdout.write("\\nline6");'],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
universal_newlines=1)
|
||||
(stdout, stderr) = p.communicate()
|
||||
if hasattr(open, 'newlines'):
|
||||
# Interpreter with universal newline support
|
||||
self.assertEqual(stdout, "line1\nline2\nline3\nline4\nline5\nline6")
|
||||
else:
|
||||
# Interpreter without universal newline support
|
||||
self.assertEqual(stdout, "line1\nline2\rline3\r\nline4\r\nline5\nline6")
|
||||
|
||||
def test_no_leaking(self):
|
||||
"""Make sure we leak no resources"""
|
||||
for i in range(1026):
|
||||
p = subprocess.Popen([sys.executable, "-c", "import sys;sys.stdout.write(sys.stdin.read())"],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
data = p.communicate("lime")[0]
|
||||
self.assertEqual(data, "lime")
|
||||
|
||||
|
||||
def test_list2cmdline(self):
|
||||
"""list2cmdline"""
|
||||
|
||||
self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
|
||||
'"a b c" d e')
|
||||
self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
|
||||
'ab\\"c \\ d')
|
||||
self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
|
||||
'a\\\\\\b "de fg" h')
|
||||
self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
|
||||
'a\\\\\\"b c d')
|
||||
self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
|
||||
'"a\\\\b c" d e')
|
||||
self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
|
||||
'"a\\\\b\\ c" d e')
|
||||
|
||||
|
||||
def test_poll(self):
|
||||
"""poll"""
|
||||
p = subprocess.Popen([sys.executable,
|
||||
"-c", "import time; time.sleep(4)"])
|
||||
while p.poll() == None:
|
||||
sys.stdout.write(".")
|
||||
sys.stdout.flush()
|
||||
time.sleep(0.5)
|
||||
# Subsequent invocations should just return the returncode
|
||||
self.assertEqual(p.poll(), 0)
|
||||
|
||||
|
||||
def test_wait(self):
|
||||
"""wait"""
|
||||
p = subprocess.Popen([sys.executable,
|
||||
"-c", "import time; time.sleep(2)"])
|
||||
self.assertEqual(p.wait(), 0)
|
||||
# Subsequent invocations should just return the returncode
|
||||
self.assertEqual(p.wait(), 0)
|
||||
|
||||
#
|
||||
# POSIX tests
|
||||
#
|
||||
if not mswindows:
|
||||
def test_exceptions(self):
|
||||
"""catched & re-raised exceptions"""
|
||||
try:
|
||||
p = subprocess.Popen([sys.executable, "-c", ""],
|
||||
cwd="/this/path/does/not/exist")
|
||||
except OSError, e:
|
||||
# The attribute child_traceback should contain "os.chdir"
|
||||
# somewhere.
|
||||
self.assertNotEqual(e.child_traceback.find("os.chdir"), -1)
|
||||
else:
|
||||
self.fail("Expected OSError")
|
||||
|
||||
def test_run_abort(self):
|
||||
"""returncode handles signal termination"""
|
||||
p = subprocess.Popen([sys.executable, "-c", "import os; os.abort()"])
|
||||
p.wait()
|
||||
self.assertEqual(-p.returncode, signal.SIGABRT)
|
||||
|
||||
def test_preexec(self):
|
||||
"""preexec function"""
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys,os;' \
|
||||
'sys.stdout.write(os.getenv("FRUIT"))'],
|
||||
stdout=subprocess.PIPE,
|
||||
preexec_fn=lambda: os.putenv("FRUIT", "apple"))
|
||||
self.assertEqual(p.stdout.read(), "apple")
|
||||
|
||||
def test_close_fds(self):
|
||||
"""close_fds"""
|
||||
# Make sure we have some fds open
|
||||
os.pipe()
|
||||
p = subprocess.Popen([sys.executable, "-c",
|
||||
'import sys,os;' \
|
||||
'sys.stdout.write(str(os.dup(0)))'],
|
||||
stdout=subprocess.PIPE, close_fds=1)
|
||||
# When all fds are closed, the next free fd should be 3.
|
||||
self.assertEqual(p.stdout.read(), "3")
|
||||
|
||||
def test_args_string(self):
|
||||
"""args is a string"""
|
||||
f, fname = self.mkstemp()
|
||||
os.write(f, "#!/bin/sh\n")
|
||||
os.write(f, "exec %s -c 'import sys; sys.exit(47)'\n" % sys.executable)
|
||||
os.close(f)
|
||||
os.chmod(fname, 0700)
|
||||
p = subprocess.Popen(fname)
|
||||
p.wait()
|
||||
self.assertEqual(p.returncode, 47)
|
||||
os.remove(fname)
|
||||
|
||||
def test_invalid_args(self):
|
||||
"""invalid arguments should raise ValueError"""
|
||||
self.assertRaises(ValueError, subprocess.call,
|
||||
[sys.executable, "-c", "import sys; sys.exit(47)"],
|
||||
startupinfo=47)
|
||||
self.assertRaises(ValueError, subprocess.call,
|
||||
[sys.executable, "-c", "import sys; sys.exit(47)"],
|
||||
creationflags=47)
|
||||
|
||||
def test_shell_sequence(self):
|
||||
"""Run command through the shell (sequence)"""
|
||||
newenv = os.environ.copy()
|
||||
newenv["FRUIT"] = "apple"
|
||||
p = subprocess.Popen(["echo $FRUIT"], shell=1,
|
||||
stdout=subprocess.PIPE,
|
||||
env=newenv)
|
||||
self.assertEqual(p.stdout.read().strip(), "apple")
|
||||
|
||||
def test_shell_string(self):
|
||||
"""Run command through the shell (string)"""
|
||||
newenv = os.environ.copy()
|
||||
newenv["FRUIT"] = "apple"
|
||||
p = subprocess.Popen("echo $FRUIT", shell=1,
|
||||
stdout=subprocess.PIPE,
|
||||
env=newenv)
|
||||
self.assertEqual(p.stdout.read().strip(), "apple")
|
||||
|
||||
def test_call_string(self):
|
||||
"""call() function with string argument on UNIX"""
|
||||
f, fname = self.mkstemp()
|
||||
os.write(f, "#!/bin/sh\n")
|
||||
os.write(f, "exec %s -c 'import sys; sys.exit(47)'\n" % sys.executable)
|
||||
os.close(f)
|
||||
os.chmod(fname, 0700)
|
||||
rc = subprocess.call(fname)
|
||||
self.assertEqual(rc, 47)
|
||||
|
||||
|
||||
#
|
||||
# Windows tests
|
||||
#
|
||||
if mswindows:
|
||||
def test_startupinfo(self):
|
||||
"""startupinfo argument"""
|
||||
# We uses hardcoded constants, because we do not want to
|
||||
# depend on win32all.
|
||||
STARTF_USESHOWWINDOW = 1
|
||||
SW_MAXIMIZE = 3
|
||||
startupinfo = subprocess.STARTUPINFO()
|
||||
startupinfo.dwFlags = STARTF_USESHOWWINDOW
|
||||
startupinfo.wShowWindow = SW_MAXIMIZE
|
||||
# Since Python is a console process, it won't be affected
|
||||
# by wShowWindow, but the argument should be silently
|
||||
# ignored
|
||||
subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
|
||||
startupinfo=startupinfo)
|
||||
|
||||
def test_creationflags(self):
|
||||
"""creationflags argument"""
|
||||
CREATE_NEW_CONSOLE = 16
|
||||
subprocess.call(sys.executable + ' -c "import time; time.sleep(2)"',
|
||||
creationflags=CREATE_NEW_CONSOLE)
|
||||
|
||||
def test_invalid_args(self):
|
||||
"""invalid arguments should raise ValueError"""
|
||||
self.assertRaises(ValueError, subprocess.call,
|
||||
[sys.executable, "-c", "import sys; sys.exit(47)"],
|
||||
preexec_fn=lambda: 1)
|
||||
self.assertRaises(ValueError, subprocess.call,
|
||||
[sys.executable, "-c", "import sys; sys.exit(47)"],
|
||||
close_fds=True)
|
||||
|
||||
def test_shell_sequence(self):
|
||||
"""Run command through the shell (sequence)"""
|
||||
newenv = os.environ.copy()
|
||||
newenv["FRUIT"] = "physalis"
|
||||
p = subprocess.Popen(["set"], shell=1,
|
||||
stdout=subprocess.PIPE,
|
||||
env=newenv)
|
||||
self.assertNotEqual(p.stdout.read().find("physalis"), -1)
|
||||
|
||||
def test_shell_string(self):
|
||||
"""Run command through the shell (string)"""
|
||||
newenv = os.environ.copy()
|
||||
newenv["FRUIT"] = "physalis"
|
||||
p = subprocess.Popen("set", shell=1,
|
||||
stdout=subprocess.PIPE,
|
||||
env=newenv)
|
||||
self.assertNotEqual(p.stdout.read().find("physalis"), -1)
|
||||
|
||||
def test_call_string(self):
|
||||
"""call() function with string argument on Windows"""
|
||||
rc = subprocess.call(sys.executable + ' -c "import sys; sys.exit(47)"')
|
||||
self.assertEqual(rc, 47)
|
||||
|
||||
|
||||
|
||||
def test_main():
|
||||
test_support.run_unittest(ProcessTestCase)
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_main()
|
||||
|
@ -44,6 +44,8 @@ Extension modules
|
||||
Library
|
||||
-------
|
||||
|
||||
- Added Peter Astrand's subprocess.py module. See PEP 327 for details.
|
||||
|
||||
- time.strptime() now properly escapes timezones and all other locale-specific
|
||||
strings for regex-specific symbols. Was breaking under Japanese Windows when
|
||||
the timezone was specified as "Tokyo (standard time)".
|
||||
|
511
PC/_subprocess.c
Normal file
511
PC/_subprocess.c
Normal file
@ -0,0 +1,511 @@
|
||||
/*
|
||||
* support routines for subprocess module
|
||||
*
|
||||
* Currently, this extension module is only required when using the
|
||||
* subprocess module on Windows, but in the future, stubs for other
|
||||
* platforms might be added here as well.
|
||||
*
|
||||
* Copyright (c) 2004 by Fredrik Lundh <fredrik@pythonware.com>
|
||||
* Copyright (c) 2004 by Secret Labs AB, http://www.pythonware.com
|
||||
* Copyright (c) 2004 by Peter Astrand <astrand@lysator.liu.se>
|
||||
*
|
||||
* By obtaining, using, and/or copying this software and/or its
|
||||
* associated documentation, you agree that you have read, understood,
|
||||
* and will comply with the following terms and conditions:
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software and
|
||||
* its associated documentation for any purpose and without fee is
|
||||
* hereby granted, provided that the above copyright notice appears in
|
||||
* all copies, and that both that copyright notice and this permission
|
||||
* notice appear in supporting documentation, and that the name of the
|
||||
* authors not be used in advertising or publicity pertaining to
|
||||
* distribution of the software without specific, written prior
|
||||
* permission.
|
||||
*
|
||||
* THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
|
||||
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
|
||||
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
|
||||
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
|
||||
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
|
||||
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
|
||||
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
*
|
||||
*/
|
||||
|
||||
/* TODO: handle unicode command lines? */
|
||||
/* TODO: handle unicode environment? */
|
||||
|
||||
#include "Python.h"
|
||||
|
||||
#define WINDOWS_LEAN_AND_MEAN
|
||||
#include "windows.h"
|
||||
|
||||
/* -------------------------------------------------------------------- */
|
||||
/* handle wrapper. note that this library uses integers when passing
|
||||
handles to a function, and handle wrappers when returning handles.
|
||||
the wrapper is used to provide Detach and Close methods */
|
||||
|
||||
typedef struct {
|
||||
PyObject_HEAD
|
||||
HANDLE handle;
|
||||
} sp_handle_object;
|
||||
|
||||
staticforward PyTypeObject sp_handle_type;
|
||||
|
||||
static PyObject*
|
||||
sp_handle_new(HANDLE handle)
|
||||
{
|
||||
sp_handle_object* self;
|
||||
|
||||
self = PyObject_NEW(sp_handle_object, &sp_handle_type);
|
||||
if (self == NULL)
|
||||
return NULL;
|
||||
|
||||
self->handle = handle;
|
||||
|
||||
return (PyObject*) self;
|
||||
}
|
||||
|
||||
static PyObject*
|
||||
sp_handle_detach(sp_handle_object* self, PyObject* args)
|
||||
{
|
||||
HANDLE handle;
|
||||
|
||||
if (!PyArg_ParseTuple(args, ":Detach"))
|
||||
return NULL;
|
||||
|
||||
handle = self->handle;
|
||||
|
||||
self->handle = NULL;
|
||||
|
||||
/* note: return the current handle, as an integer */
|
||||
return PyInt_FromLong((long) handle);
|
||||
}
|
||||
|
||||
static PyObject*
|
||||
sp_handle_close(sp_handle_object* self, PyObject* args)
|
||||
{
|
||||
if (!PyArg_ParseTuple(args, ":Close"))
|
||||
return NULL;
|
||||
|
||||
if (self->handle != INVALID_HANDLE_VALUE) {
|
||||
CloseHandle(self->handle);
|
||||
self->handle = INVALID_HANDLE_VALUE;
|
||||
}
|
||||
Py_INCREF(Py_None);
|
||||
return Py_None;
|
||||
}
|
||||
|
||||
static void
|
||||
sp_handle_dealloc(sp_handle_object* self)
|
||||
{
|
||||
if (self->handle != INVALID_HANDLE_VALUE)
|
||||
CloseHandle(self->handle);
|
||||
PyMem_DEL(self);
|
||||
}
|
||||
|
||||
static PyMethodDef sp_handle_methods[] = {
|
||||
{"Detach", (PyCFunction) sp_handle_detach, 1},
|
||||
{"Close", (PyCFunction) sp_handle_close, 1},
|
||||
{NULL, NULL}
|
||||
};
|
||||
|
||||
static PyObject*
|
||||
sp_handle_getattr(sp_handle_object* self, char* name)
|
||||
{
|
||||
return Py_FindMethod(sp_handle_methods, (PyObject*) self, name);
|
||||
}
|
||||
|
||||
static PyObject*
|
||||
sp_handle_as_int(sp_handle_object* self)
|
||||
{
|
||||
return PyInt_FromLong((long) self->handle);
|
||||
}
|
||||
|
||||
static PyNumberMethods sp_handle_as_number;
|
||||
|
||||
statichere PyTypeObject sp_handle_type = {
|
||||
PyObject_HEAD_INIT(NULL)
|
||||
0, /*ob_size*/
|
||||
"_subprocess_handle", sizeof(sp_handle_object), 0,
|
||||
(destructor) sp_handle_dealloc, /*tp_dealloc*/
|
||||
0, /*tp_print*/
|
||||
(getattrfunc) sp_handle_getattr, /*tp_getattr*/
|
||||
0, /*tp_setattr*/
|
||||
0, /*tp_compare*/
|
||||
0, /*tp_repr*/
|
||||
&sp_handle_as_number, /*tp_as_number */
|
||||
0, /*tp_as_sequence */
|
||||
0, /*tp_as_mapping */
|
||||
0 /*tp_hash*/
|
||||
};
|
||||
|
||||
/* -------------------------------------------------------------------- */
|
||||
/* windows API functions */
|
||||
|
||||
static PyObject *
|
||||
sp_GetStdHandle(PyObject* self, PyObject* args)
|
||||
{
|
||||
HANDLE handle;
|
||||
|
||||
int std_handle;
|
||||
if (!PyArg_ParseTuple(args, "i:GetStdHandle", &std_handle))
|
||||
return NULL;
|
||||
|
||||
Py_BEGIN_ALLOW_THREADS
|
||||
handle = GetStdHandle((DWORD) std_handle);
|
||||
Py_END_ALLOW_THREADS
|
||||
|
||||
if (handle == INVALID_HANDLE_VALUE)
|
||||
return PyErr_SetFromWindowsErr(GetLastError());
|
||||
|
||||
if (!handle) {
|
||||
Py_INCREF(Py_None);
|
||||
return Py_None;
|
||||
}
|
||||
|
||||
/* note: returns integer, not handle object */
|
||||
return PyInt_FromLong((long) handle);
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
sp_GetCurrentProcess(PyObject* self, PyObject* args)
|
||||
{
|
||||
if (!PyArg_ParseTuple(args, ":GetCurrentProcess"))
|
||||
return NULL;
|
||||
|
||||
return sp_handle_new(GetCurrentProcess());
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
sp_DuplicateHandle(PyObject* self, PyObject* args)
|
||||
{
|
||||
HANDLE target_handle;
|
||||
BOOL result;
|
||||
|
||||
long source_process_handle;
|
||||
long source_handle;
|
||||
long target_process_handle;
|
||||
int desired_access;
|
||||
int inherit_handle;
|
||||
int options = 0;
|
||||
if (!PyArg_ParseTuple(args, "lllii|i:DuplicateHandle",
|
||||
&source_process_handle, &source_handle,
|
||||
&target_process_handle,
|
||||
&desired_access, &inherit_handle, &options))
|
||||
return NULL;
|
||||
|
||||
Py_BEGIN_ALLOW_THREADS
|
||||
result = DuplicateHandle(
|
||||
(HANDLE) source_process_handle, (HANDLE) source_handle,
|
||||
(HANDLE) target_process_handle, &target_handle, desired_access,
|
||||
inherit_handle, options
|
||||
);
|
||||
Py_END_ALLOW_THREADS
|
||||
|
||||
if (!result)
|
||||
return PyErr_SetFromWindowsErr(GetLastError());
|
||||
|
||||
return sp_handle_new(target_handle);
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
sp_CreatePipe(PyObject* self, PyObject* args)
|
||||
{
|
||||
HANDLE read_pipe;
|
||||
HANDLE write_pipe;
|
||||
BOOL result;
|
||||
|
||||
PyObject* pipe_attributes; /* ignored */
|
||||
int size;
|
||||
if (!PyArg_ParseTuple(args, "Oi:CreatePipe", &pipe_attributes, &size))
|
||||
return NULL;
|
||||
|
||||
Py_BEGIN_ALLOW_THREADS
|
||||
result = CreatePipe(&read_pipe, &write_pipe, NULL, size);
|
||||
Py_END_ALLOW_THREADS
|
||||
|
||||
if (!result)
|
||||
return PyErr_SetFromWindowsErr(GetLastError());
|
||||
|
||||
return Py_BuildValue(
|
||||
"NN", sp_handle_new(read_pipe), sp_handle_new(write_pipe)
|
||||
);
|
||||
}
|
||||
|
||||
/* helpers for createprocess */
|
||||
|
||||
static int
|
||||
getint(PyObject* obj, char* name)
|
||||
{
|
||||
PyObject* value;
|
||||
value = PyObject_GetAttrString(obj, name);
|
||||
if (!value) {
|
||||
PyErr_Clear(); /* FIXME: propagate error? */
|
||||
return 0;
|
||||
}
|
||||
return (int) PyInt_AsLong(value);
|
||||
}
|
||||
|
||||
static HANDLE
|
||||
gethandle(PyObject* obj, char* name)
|
||||
{
|
||||
sp_handle_object* value;
|
||||
value = (sp_handle_object*) PyObject_GetAttrString(obj, name);
|
||||
if (!value) {
|
||||
PyErr_Clear(); /* FIXME: propagate error? */
|
||||
return NULL;
|
||||
}
|
||||
if (value->ob_type != &sp_handle_type)
|
||||
return NULL;
|
||||
return value->handle;
|
||||
}
|
||||
|
||||
static PyObject*
|
||||
getenvironment(PyObject* environment)
|
||||
{
|
||||
int i, envsize;
|
||||
PyObject* out = NULL;
|
||||
PyObject* keys;
|
||||
PyObject* values;
|
||||
char* p;
|
||||
|
||||
/* convert environment dictionary to windows enviroment string */
|
||||
|
||||
if (!PyMapping_Check(environment)) {
|
||||
PyErr_SetString(
|
||||
PyExc_TypeError, "environment must be dictionary or None"
|
||||
);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
envsize = PyMapping_Length(environment);
|
||||
|
||||
keys = PyMapping_Keys(environment);
|
||||
values = PyMapping_Values(environment);
|
||||
if (!keys || !values)
|
||||
goto error;
|
||||
|
||||
out = PyString_FromStringAndSize(NULL, 2048);
|
||||
if (!out)
|
||||
goto error;
|
||||
|
||||
p = PyString_AS_STRING(out);
|
||||
|
||||
for (i = 0; i < envsize; i++) {
|
||||
int ksize, vsize, totalsize;
|
||||
PyObject* key = PyList_GET_ITEM(keys, i);
|
||||
PyObject* value = PyList_GET_ITEM(values, i);
|
||||
if (!PyString_Check(key) || !PyString_Check(value)) {
|
||||
PyErr_SetString(
|
||||
PyExc_TypeError, "environment can only contain strings"
|
||||
);
|
||||
goto error;
|
||||
}
|
||||
ksize = PyString_GET_SIZE(key);
|
||||
vsize = PyString_GET_SIZE(value);
|
||||
totalsize = (p - PyString_AS_STRING(out)) + ksize + 1 + vsize + 1 + 1;
|
||||
if (totalsize > PyString_GET_SIZE(out)) {
|
||||
int offset = p - PyString_AS_STRING(out);
|
||||
_PyString_Resize(&out, totalsize + 1024);
|
||||
p = PyString_AS_STRING(out) + offset;
|
||||
}
|
||||
memcpy(p, PyString_AS_STRING(key), ksize); p += ksize; *p++ = '=';
|
||||
memcpy(p, PyString_AS_STRING(value), vsize); p += vsize; *p++ = '\0';
|
||||
}
|
||||
|
||||
/* add trailing null byte */
|
||||
*p++ = '\0';
|
||||
|
||||
_PyString_Resize(&out, p - PyString_AS_STRING(out));
|
||||
|
||||
/* PyObject_Print(out, stdout, 0); */
|
||||
|
||||
return out;
|
||||
|
||||
error:
|
||||
Py_XDECREF(out);
|
||||
Py_XDECREF(keys);
|
||||
Py_XDECREF(values);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
sp_CreateProcess(PyObject* self, PyObject* args)
|
||||
{
|
||||
BOOL result;
|
||||
PROCESS_INFORMATION pi;
|
||||
STARTUPINFO si;
|
||||
PyObject* environment;
|
||||
|
||||
char* application_name;
|
||||
char* command_line;
|
||||
PyObject* process_attributes; /* ignored */
|
||||
PyObject* thread_attributes; /* ignored */
|
||||
int inherit_handles;
|
||||
int creation_flags;
|
||||
PyObject* env_mapping;
|
||||
char* current_directory;
|
||||
PyObject* startup_info;
|
||||
if (!PyArg_ParseTuple(args, "zzOOiiOzO:CreateProcess",
|
||||
&application_name, &command_line,
|
||||
&process_attributes, &thread_attributes,
|
||||
&inherit_handles, &creation_flags,
|
||||
&env_mapping, ¤t_directory, &startup_info))
|
||||
return NULL;
|
||||
|
||||
ZeroMemory(&si, sizeof(si));
|
||||
si.cb = sizeof(si);
|
||||
|
||||
/* note: we only support a small subset of all SI attributes */
|
||||
si.dwFlags = getint(startup_info, "dwFlags");
|
||||
si.hStdInput = gethandle(startup_info, "hStdInput");
|
||||
si.hStdOutput = gethandle(startup_info, "hStdOutput");
|
||||
si.hStdError = gethandle(startup_info, "hStdError");
|
||||
|
||||
if (env_mapping == Py_None)
|
||||
environment = NULL;
|
||||
else {
|
||||
environment = getenvironment(env_mapping);
|
||||
if (!environment)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
Py_BEGIN_ALLOW_THREADS
|
||||
result = CreateProcess(
|
||||
application_name, command_line, NULL, NULL, inherit_handles,
|
||||
creation_flags, environment ? PyString_AS_STRING(environment) : NULL,
|
||||
current_directory, &si, &pi
|
||||
);
|
||||
Py_END_ALLOW_THREADS
|
||||
|
||||
Py_XDECREF(environment);
|
||||
|
||||
if (!result)
|
||||
return PyErr_SetFromWindowsErr(GetLastError());
|
||||
|
||||
return Py_BuildValue(
|
||||
"NNii", sp_handle_new(pi.hProcess), sp_handle_new(pi.hThread),
|
||||
pi.dwProcessId, pi.dwThreadId
|
||||
);
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
sp_GetExitCodeProcess(PyObject* self, PyObject* args)
|
||||
{
|
||||
DWORD exit_code;
|
||||
BOOL result;
|
||||
|
||||
long process;
|
||||
if (!PyArg_ParseTuple(args, "l:GetExitCodeProcess", &process))
|
||||
return NULL;
|
||||
|
||||
result = GetExitCodeProcess((HANDLE) process, &exit_code);
|
||||
|
||||
if (!result)
|
||||
return PyErr_SetFromWindowsErr(GetLastError());
|
||||
|
||||
return PyInt_FromLong(exit_code);
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
sp_WaitForSingleObject(PyObject* self, PyObject* args)
|
||||
{
|
||||
DWORD result;
|
||||
|
||||
long handle;
|
||||
int milliseconds;
|
||||
if (!PyArg_ParseTuple(args, "li:WaitForSingleObject",
|
||||
&handle, &milliseconds))
|
||||
return NULL;
|
||||
|
||||
Py_BEGIN_ALLOW_THREADS
|
||||
result = WaitForSingleObject((HANDLE) handle, (DWORD) milliseconds);
|
||||
Py_END_ALLOW_THREADS
|
||||
|
||||
if (result == WAIT_FAILED)
|
||||
return PyErr_SetFromWindowsErr(GetLastError());
|
||||
|
||||
return PyInt_FromLong((int) result);
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
sp_GetVersion(PyObject* self, PyObject* args)
|
||||
{
|
||||
if (!PyArg_ParseTuple(args, ":GetVersion"))
|
||||
return NULL;
|
||||
|
||||
return PyInt_FromLong((int) GetVersion());
|
||||
}
|
||||
|
||||
static PyObject *
|
||||
sp_GetModuleFileName(PyObject* self, PyObject* args)
|
||||
{
|
||||
BOOL result;
|
||||
long module;
|
||||
TCHAR filename[MAX_PATH];
|
||||
|
||||
if (!PyArg_ParseTuple(args, "l:GetModuleFileName", &module))
|
||||
return NULL;
|
||||
|
||||
result = GetModuleFileName((HMODULE)module, filename, MAX_PATH);
|
||||
filename[MAX_PATH-1] = '\0';
|
||||
|
||||
if (!result)
|
||||
return PyErr_SetFromWindowsErr(GetLastError());
|
||||
|
||||
return PyString_FromString(filename);
|
||||
}
|
||||
|
||||
static PyMethodDef sp_functions[] = {
|
||||
{"GetStdHandle", sp_GetStdHandle, METH_VARARGS},
|
||||
{"GetCurrentProcess", sp_GetCurrentProcess, METH_VARARGS},
|
||||
{"DuplicateHandle", sp_DuplicateHandle, METH_VARARGS},
|
||||
{"CreatePipe", sp_CreatePipe, METH_VARARGS},
|
||||
{"CreateProcess", sp_CreateProcess, METH_VARARGS},
|
||||
{"GetExitCodeProcess", sp_GetExitCodeProcess, METH_VARARGS},
|
||||
{"WaitForSingleObject", sp_WaitForSingleObject, METH_VARARGS},
|
||||
{"GetVersion", sp_GetVersion, METH_VARARGS},
|
||||
{"GetModuleFileName", sp_GetModuleFileName, METH_VARARGS},
|
||||
{NULL, NULL}
|
||||
};
|
||||
|
||||
/* -------------------------------------------------------------------- */
|
||||
|
||||
static void
|
||||
defint(PyObject* d, const char* name, int value)
|
||||
{
|
||||
PyObject* v = PyInt_FromLong((long) value);
|
||||
if (v) {
|
||||
PyDict_SetItemString(d, (char*) name, v);
|
||||
Py_DECREF(v);
|
||||
}
|
||||
}
|
||||
|
||||
#if PY_VERSION_HEX >= 0x02030000
|
||||
PyMODINIT_FUNC
|
||||
#else
|
||||
DL_EXPORT(void)
|
||||
#endif
|
||||
init_subprocess()
|
||||
{
|
||||
PyObject *d;
|
||||
PyObject *m;
|
||||
|
||||
/* patch up object descriptors */
|
||||
sp_handle_type.ob_type = &PyType_Type;
|
||||
sp_handle_as_number.nb_int = (unaryfunc) sp_handle_as_int;
|
||||
|
||||
m = Py_InitModule("_subprocess", sp_functions);
|
||||
d = PyModule_GetDict(m);
|
||||
|
||||
/* constants */
|
||||
defint(d, "STD_INPUT_HANDLE", STD_INPUT_HANDLE);
|
||||
defint(d, "STD_OUTPUT_HANDLE", STD_OUTPUT_HANDLE);
|
||||
defint(d, "STD_ERROR_HANDLE", STD_ERROR_HANDLE);
|
||||
defint(d, "DUPLICATE_SAME_ACCESS", DUPLICATE_SAME_ACCESS);
|
||||
defint(d, "STARTF_USESTDHANDLES", STARTF_USESTDHANDLES);
|
||||
defint(d, "INFINITE", INFINITE);
|
||||
defint(d, "WAIT_OBJECT_0", WAIT_OBJECT_0);
|
||||
defint(d, "CREATE_NEW_CONSOLE", CREATE_NEW_CONSOLE);
|
||||
}
|
Loading…
Reference in New Issue
Block a user