forked from cirosantilli/python-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·53 lines (43 loc) · 1.51 KB
/
main.py
File metadata and controls
executable file
·53 lines (43 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python
import os
import subprocess
import sys
commands = ['python', 'a.py', 'arg 1', 'arg 2']
try:
process = subprocess.Popen(
commands,
shell = False,
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
universal_newlines = True
)
except OSError:
#typically gets here if the executable is not found
sys.stderr.write(' '.join(commands) + '\nfailed')
stdin = 'stdin1\nstdin2'
# Waits for process to finish.
# We'd need the lower level process.std[in,out,err] to do multiple communications:
# http://stackoverflow.com/questions/3065060/communicate-multiple-times-with-a-process-without-breaking-the-pipe
stdout, stderr = process.communicate(stdin)
assert stdout == 'stdout:\nstdin1\nstdin2\n'
assert stderr == 'stderr:\narg 1\narg 2\n'
# Wait for process to end and get exit status:
exit_status = process.wait()
assert exit_status == 0
#does not wait for process to end, None if process not yet terminated:
#return_code = process.poll()
if '#check method present':
# http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
def command_present(command):
import distutils.spawn
# Only in path:
return distutils.spawn.find_executable(command)
print "command_present"
commands = ['ls', 'not-present']
for command in commands:
sys.stdout.write(command + ': ')
if command_present(command):
print "yes"
else:
print "no"