Python 2中无法通过独立进程启动ngrok,原命令失效求解决
Hey, let's figure out why your ngrok command stopped working with subprocess!
The core issue here is how you're passing the command to subprocess.Popen. When you use bashCommand.split(), Python just splits the string on whitespace—it doesn't understand shell-specific syntax like input/output redirections (</dev/null, >/dev/null, 2>&1) or the background & symbol. All those extra bits get treated as arguments for ngrok, which only expects a single port/address to tunnel to. That's exactly why you're seeing the error about specifying 5 arguments instead of 1.
As for why it worked a few months back? Maybe you had shell=True in your code before and accidentally removed it, or your environment had a quirk that made the split behave differently. Either way, let's fix it properly.
Fix 1: Let the shell handle the command (simpler approach)
Add shell=True to your Popen call, and pass the full command string directly (don't split it). This tells subprocess to hand the entire command to the system shell, which will correctly parse the redirections and backgrounding logic:
bashCommand = "nohup /Users/myname/ngrok http 8889 </dev/null >/dev/null 2>&1 &" process = subprocess.Popen(bashCommand, shell=True, stdout=subprocess.PIPE) output, error = process.communicate()
Fix 2: Avoid shell=True (more secure option)
If you want to skip using shell=True (it's safer because it eliminates shell injection risks), you can handle redirections and backgrounding directly with subprocess arguments:
import subprocess import os # Open /dev/null for input/output handling with open(os.devnull, 'r+') as devnull: process = subprocess.Popen( ['/Users/myname/ngrok', 'http', '8889'], stdin=devnull, stdout=devnull, stderr=devnull, start_new_session=True # Mimics nohup's behavior to keep the process running after your script exits )
内容的提问来源于stack exchange,提问作者Sankalp

