subprocess字符串变量转换问题:subprocess.call变量调用异常
Hey there! Let's work through why your source and destination variables aren't playing nice with subprocess.call() — this is a super common pitfall when you're new to the subprocess module, so don't sweat it.
subprocess.call() with Path Variables 1. You're passing a single string instead of an argument list (default behavior)
By default, subprocess.call() expects a list of individual arguments, not a single combined string. If you wrote code like this:
source = "/home/user/my files/data.txt" destination = "/home/user/backup" subprocess.call(f"cp {source} {destination}")
It’ll fail because subprocess tries to run a command literally named cp /home/user/my files/data.txt /home/user/backup (which doesn’t exist) instead of splitting it into separate parts: cp, /home/user/my files/data.txt, /home/user/backup.
The Fix: Pass a list of arguments instead — this is also the safest approach (no shell injection risks) and handles spaces in paths automatically:
subprocess.call(["cp", source, destination])
2. You're using shell=True but not escaping special characters
If you need shell=True (for example, to use shell features like wildcards or pipes), you have to account for spaces, quotes, or special characters in your source/destination paths. A path like /my docs/photo.jpg will break a raw string concatenation.
Safer Fix for shell=True: Use shlex.quote() to properly escape your variables:
import shlex subprocess.call(f"cp {shlex.quote(source)} {shlex.quote(destination)}", shell=True)
Just keep in mind: shell=True is less secure if your variables come from untrusted user input.
3. You're using a shell built-in (like source) instead of an executable
If your command uses source (a bash built-in, not a standalone executable), you can’t call it directly with subprocess. You need to run it through a shell explicitly:
# Example: Sourcing a script then copying a file subprocess.call(["bash", "-c", f"source {shlex.quote(source_script)} && cp {shlex.quote(source_file)} {shlex.quote(destination)}"])
Quick Debug Checklist
- Print
sourceanddestinationright before calling subprocess to confirm they hold the correct paths. - If you get a "command not found" error, you’re probably passing a string without
shell=Truewhen you should be using an argument list. - If paths have spaces, stick to the list syntax or use
shlex.quote()withshell=True.
内容的提问来源于stack exchange,提问作者Frankie

