MADRID — The leader of Spain’s main opposition Socialist Party on Wednesday narrowly escaped an attempt by senior members of his own party to oust him, after a string of electoral defeats and amid a lengthy stalemate in Spanish politics.

But the future of the Socialists’ leader, Pedro Sánchez, still hangs in the balance, after 17 of the current 35 members of the party’s executive committee unexpectedly announced on Wednesday that they would resign as a protest against Mr. Sánchez for prolonging the deadlock.

In response to the rebellion, however, Mr. Sánchez indicated that he would go ahead with his plan to hold primary elections in which party members will vote on his leadership, rather than allow only members of the executive committee to decide his fate. Such primary elections, however, have been tentatively scheduled for next month, probably about a week before an Oct. 31 deadline to form a new government and avoid a third election.

The internal revolt against Mr. Sánchez and the battle over the Socialist Party leadership are the first unexpected moves that could shift Spanish politics since inconclusive national elections last December. Whatever the outcome, the turmoil within the Socialist Party is likely to reinforce the position of Mariano Rajoy, the caretaker conservative prime minister, who is now facing a Socialist opponent fighting for his own political survival.