How to check if command were done?
<p>I'am trying to do some stuff with git. I wonder how would I make the <strong>if statement</strong> argument to check if that command were done correctly:</p>

<pre><code>git checkout master &amp;&amp; git reset --hard &amp;&amp; git fetch &amp;&amp; git pull
</code></pre>

<p>I was trying with check if output is equal to if statement but I guess it's a bad idea. Here is a code:</p>

<pre><code>#!/usr/bin/python3
import os
import subprocess
import time

while True:

x = subprocess.getoutput("git checkout master &amp;&amp; git reset --hard &amp;&amp; git fetch &amp;&amp; git pull")

   if x is "Some text":
    print('Some actions there')

time.sleep(3600)
</code></pre>

<p>So I wonder is there any way to check if command where done or not.</p>

<p>Use <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">subprocess</a> module, but execute each of your command with <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen" rel="nofollow">Popen</a> or <a href="https://docs.python.org/3/library/subprocess.html#subprocess.run" rel="nofollow">run</a>. I would recommend the latter, as its returned type has useful <a href="https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess.check_returncode" rel="nofollow">check_returncode()</a> method. Use <a href="https://docs.python.org/3/library/shlex.html#shlex.split" rel="nofollow">shlex.split()</a> to turn command into list of its parts.</p>

<p>Basically what you want to do is something like:</p>

<pre><code>import subprocess, shlex
for (cmd in ("git checkout master", "git reset --hard", "git fetch", "git pull")):
    subprocess.run(shlex.split(cmd)).check_returncode()
</code></pre>

<p>Disclaimer: this was written ad-hoc and not tested. It is only supposed to show you how to get there, not do that for you all the way.</p>

python linux python-3.x