Python3 os.system()执行报错:sh: 2: Syntax error: "|" unexpected
os.system call Hey there, let's break down why you're hitting that syntax error and fix it properly—we'll also make your code way safer in the process.
The Root Cause
That error pops up because os.system() passes your entire command string to the shell for parsing. If your password has any shell-special characters (spaces, quotes, |, &, etc.), it'll split your command into unexpected chunks, throwing the syntax error. On top of that, hardcoding or embedding your password directly in a command string is a major security risk—it can show up in process lists or system logs.
The Better Solution: Use subprocess (Highly Recommended)
os.system() is legacy functionality; Python's official docs strongly recommend using the subprocess module instead. It gives you more control, avoids shell injection risks, and eliminates the syntax issues you're facing. Here's how to rewrite your code safely:
We'll send the password directly to sudo via stdin (which is exactly what the -S flag is designed for) instead of echoing it in the command line, and handle file writing with Python instead of shell redirection.
import subprocess password = "your_actual_password" file_path = "/path/to/your/target/file" # Open the target file and redirect the output of `sudo date` to it with open(file_path, "w") as output_file: # Send the password as bytes to sudo's stdin result = subprocess.run( ["sudo", "-S", "date"], input=password.encode("utf-8"), stdout=output_file, stderr=subprocess.PIPE, text=False # We're sending bytes, so keep this False ) # Optional: Verify if the command succeeded if result.returncode == 0: print("Command executed successfully!") else: print(f"Error occurred: {result.stderr.decode('utf-8')}")
This approach avoids shell parsing entirely because we're using a list of command arguments instead of a string, and the password is never exposed in a command line. No more syntax errors, and way more secure.
If You Must Use os.system() (Not Recommended)
If you have to stick with os.system() for some reason, you need to properly escape all shell-special characters in your password and file path using shlex.quote():
import os import shlex password = "your_actual_password" file_path = "/path/to/your/target/file" # Escape special characters to avoid shell parsing issues escaped_password = shlex.quote(password) escaped_file_path = shlex.quote(file_path) # Construct the command safely os.system(f"echo {escaped_password} | sudo -S date > {escaped_file_path}")
⚠️ Critical Note: This method is still insecure—your password might still be visible in system process logs. Use the subprocess approach whenever possible.
内容的提问来源于stack exchange,提问作者Prabhakar Jha

