简体   繁体   中英

Why does my subprocess.call work only when shell = True? Python

I am using subprocess.call() to execute commands from a specific directory.

Without using shell = True

scrcpyPath = "C:\\Users\\H\\Downloads\\scrcpy-win64-v1.14"
subprocess.call(["scrcpy", "--window-title", "'Mydevice'"], cwd = scrcpyPath)

I get the following error

FileNotFoundError: [WinError 2] The system cannot find the file specified.

I have managed to make it work using `shell = True'

subprocess.call(f"scrcpy --window-title 'Mydevice'", cwd = scrcpyPath, shell = True)

but it stops working when I add whitespace in the window title Mydevice .

subprocess.call(f"scrcpy --window-title 'My device'", cwd = scrcpyPath, shell = True)

I get the following error

ERROR: Unexpected additional argument: 1'

The reason I am using a formatted string is that I want the window title to be a variable, but again - it does not work when I add whitespace.

subprocess.call(f"scrcpy --window-title 'Device {deviceName}'", cwd = scrcpyPath, shell = True)

I found the solution. I think I was wrongly using cwd .

subprocess.call([f"{scrcpyPath}\\scrcpy", "--window-title", f"'{deviceName}'"])

You didn't split your arguments properly; basically any space-separation in the command-line should be separate arguments, and no shell quoting is needed when they're passed as separate arguments. What you wanted was:

subprocess.call(["scrcpy", "--window-title", "Mydevice"], cwd=scrcpyPath)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM