Locke (6-3) scattered six hits, struck out three and walked one on the mound, improving to 4-0 in his last five starts.
Ike Davis added a mammoth two-run homer for the Pirates, who won the final two tests of this three-game set to draw closer to the NL Wild Card-leading Cardinals.
Russell Martin added two hits and Andrew McCutchen drove in a run for Pittsburgh, which drew within 2 1/2 games of the Cardinals and also inched closer to the San Francisco Giants, the leader for the second wild card.
St. Louis starting pitcher Adam Wainwright (15-9) was tagged with the loss, failing for a second straight start to become the first pitcher to 16 wins in the majors this season. The right-hander was charged with three runs on eight hits, striking out five and walking one, over six frames.
Matt Holliday homered and Daniel Descalso had a pair of hits to lead the Cardinals, who have dropped two in a row and four of six.
Davis got the Pirates going with his two-run homer in the second inning that traveled an estimated 433 feet.
The Cards got a run back in the third when Holliday hit a solo homer, but the Pirates regained the two-run edge when Locke singled and later scored on Andrew McCutchen's sac fly in the third.
Locke was locked in after the two-out solo homer by Holliday, retiring 13 of the next 15 batters he faced before Matt Carpenter led off the eighth inning with a walk. After Locke got Randal Grichuk to fly out to left, he was lifted in favor of reliever Tony Watson, who got out of the inning by striking out Holliday and getting Matt Adams to ground out to second.
Mark Melancon worked around a lead-off hit in the ninth by Jhonny Peralta to pick up his 24th save of the season.