I would like to write a simple python script which will be able to clone a git repository into desired directory. I used try...except construction to be able to catch all exceptions however it looks like I am not able to handle 'fatal' properly.
#!/usr/bin/env python
import subprocess
try:
subprocess.check_call(['git', 'clone', 'git clone git@some_repo', '/tmp/some_directory'])
except Exception:
print "There was a problem during repository configuration"
The output of the script above:
fatal: repository 'git clone git@some_repo' does not exist
There was a problem during repository configuration
To be more specific, I was rather expecting to get only the "There was a ..." message. Why do I get a 'fatal' message also?
You need to capture STDERR
of your subprocess.check_call()
execution. See Catch stderr in subprocess.check_call without using subprocess.PIPE
for details.
The message you are seeing is produced by the git
command.
If you want to prevent that message from appearing you should redirect either standard error or all output to /dev/null
through a shell, like:
subprocess.check_call(['git', 'clone', 'git clone git@some_repo', '/tmp/some_directory', '2&>/dev/null'], shell=True)
However, I'd recommend against that practice since you lose information on the actual cause of error.
As previously specified you need to capture the standard error. Also, as the documentation specifies, subprocess.check_call()
just raises an exception when the return code is non-zero.
So, you could mimic the behavior as follows:
#!/usr/bin/env python
import subprocess
def clone_repository(): # customize your function parameters
# prepare the arguments with your function parameters
arguments = ['git', 'clone', 'git clone git@some_repo', '/tmp/some_directory']
git_proc = subprocess.Popen(arguments)
stdout, stderr = git_proc.communicate()
if git_proc.returncode != 0:
raise subprocess.CalledProcessError(arguments, git_proc.returncode)
return stdout, stderr
try:
stdout, stderr = clone_repository()
except (OSError, ValueError) as e:
# this errors out when the arguments are invalid (ValueError)
# or when there is an underlying file missing, etc (OSError)
# put the print that you require for these errors
pass
except subprocess.CalledProcessError:
# you could use stderr to determine the underlying error
print "There was a problem during repository configuration"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.