Python - OS Command

Card Puncher Data Processing

About

OS Command (Interactive Programming - Command) in Python

Example

https://docs.python.org/3/library/subprocess.html#popen-constructor

p = subprocess.Popen(['git', 'log', '@{u}..'], stderr=subprocess.STDOUT, cwd=directory,
                             stdout=subprocess.PIPE)
try:
	# Get the stdout in byte
	bstdouts = p.communicate(timeout=15)[0]
	# Byte to string
	stdouts = str(bstdouts, 'utf-8')
except subprocess.TimeoutExpired:
	p.kill()
	stdouts = p.communicate()[0]
return_code = p.returncode
if return_code != 0:
	print("Error: the directory (" + directory + ") returns the error code " + str(return_code))
	print(stdouts)
else:
	if stdouts != '':
		print("Directory (" + directory + ") returns the following:")
		print(stdouts)

where:

  • ['git', 'log', '@{u}..'] are args. They should be a sequence of program arguments or else a single string.
  • stderr=subprocess.STDOUT redirects stdout to stderr
  • stdout=subprocess.PIPE to get other than None in the result tuple of p.communicate (ie you need to give stdout=PIPE and/or stderr=PIPE ).







Share this page:
Follow us:
Task Runner