![](/img/trans.png)
[英]Python running in Windows subprocess.call with spaces and parameters
[英]running command via subprocess on Windows with spaces in filenames
要在python中为Windows运行命令,我需要执行以下操作:
import subprocess
subprocess.check_output(lsCommand, shell=True)
其中, lsCommand
是组成bash命令的字符串列表。 这行得通,除非它包含一些带有空格的输入。 例如,复制+更改名称:
尝试执行cp "test 123" test123
:
lsCommand = ['cp', 'test 123', 'test123']
subprocess.check_output(lsCommand, shell=True)
失败,因为它认为我正在尝试执行cp "test" "123" test123
。 错误(正在使用Google存储设备):
python: can't open file 'c:\GSUtil\gsutil.py cp -n gs://folderl/test': [Errno 22] Invalid argument
然后我尝试
subprocess.check_output('cp "test 123" test123', shell=True)
一样 有任何想法吗?
cp
不是内部命令 ,因此不需要shell=True
( 尽管您可能需要指定cp.exe
的完整路径 )。
Windows上用于启动新子进程的内部接口使用字符串,即,具体应用程序如何解释命令行。 在这种情况下,默认的MS C运行时规则(在subprocess.list2cmdline subprocess.list2cmdline()
,如果您在Windows上传递列表,则将隐式调用该规则subprocess.list2cmdline()
:
#!/usr/bin/env python
from subprocess import check_call
check_call(['cp', 'test 123', 'test123'])
如果要使用shell=True
则解释命令行的程序为cmd.exe
,则应使用其转义规则( 例如^
是元字符 ),并按原样将字符串作为字符串传递(如您所见)在Windows控制台中):
check_call('copy /Y /B "test 123" test123', shell=True)
显然,您无需启动外部进程即可在Python中复制文件 :
import shutil
shutil.copy('test 123', 'test123')
对于Ubuntu:
subprocess.check_output(['list', 'of', 'commands with spaces'])
对于Windows:
subprocess.check_output('single command "string with spaces"')
感谢您提供不需要shell=True
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.