Python中将命令行命令转为os.system/subprocess调用报错的问询
Hey there, let's sort out why your command is throwing those errors!
The Root Cause
When you split your full command string into a list and pass it to subprocess.call(), you're telling Python to run the cat command directly with all those parts as arguments. That means cat is trying to open files named |, sort, >, etc.—which obviously don't exist, hence the "No such file or directory" errors.
The pipe (|) and redirection (>) are shell features, not arguments to cat. By default, subprocess doesn't use the shell to parse these, so they get treated as regular filename arguments.
Solution 1: Use shell=True (Quick Fix)
If you want to run the command exactly as you would in a terminal, you can tell subprocess to use the shell to parse the entire command string. Here's how:
import subprocess command = "cat /home/norman/conf/second.txt | sort | uniq > /home/norman/conf/third.txt" subprocess.call(command, shell=True)
Note: Be careful with shell=True if your command includes user-provided input—it can lead to shell injection vulnerabilities. Since your command uses fixed paths, this is safe here.
Solution 2: Avoid Shell (Recommended, More Secure)
For better security and control, you can chain the commands using subprocess pipes directly, without relying on the shell. This is the preferred approach for production code:
import subprocess # Step 1: Read the file with cat cat_process = subprocess.Popen( ["cat", "/home/norman/conf/second.txt"], stdout=subprocess.PIPE ) # Step 2: Pipe cat's output to sort sort_process = subprocess.Popen( ["sort"], stdin=cat_process.stdout, stdout=subprocess.PIPE ) cat_process.stdout.close() # Allow cat to receive SIGPIPE if sort exits early # Step 3: Pipe sort's output to uniq, and write to the output file with open("/home/norman/conf/third.txt", "w") as output_file: uniq_process = subprocess.Popen( ["uniq"], stdin=sort_process.stdout, stdout=output_file ) sort_process.stdout.close() # Wait for the final process to finish uniq_process.wait()
Alternatively, you can use subprocess.run with a controlled shell invocation:
import subprocess with open("/home/norman/conf/third.txt", "w") as outfile: subprocess.run( ["sh", "-c", "cat /home/norman/conf/second.txt | sort | uniq"], stdout=outfile )
Either way, this avoids treating shell operators as command arguments, which fixes your original error.
内容的提问来源于stack exchange,提问作者Buteman

