2016-03-31 16 views
0

にスペースを使用してWindows上でサブプロセスを経由してコマンドを実行している、私が行いますはWindows用、Pythonでコマンドを実行するには、ファイル名

lsCommandはbashコマンドを構成する文字列のリストである
import subprocess 
subprocess.check_output(lsCommand, shell=True) 

。空白を含む入力がある場合を除いて、これは機能します。

がしようとするとcp "test 123" test123を行うには:たとえば、名前を変更+コピー、それは私がcp "test" "123" test123をやろうとしています考えているので

lsCommand = ['cp', 'test 123', 'test123'] 
subprocess.check_output(lsCommand, shell=True) 

は失敗します。エラー(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) 

同じたわごとをしてみてください。何か案は?

+1

なぜ 'shell = True'を使用していますか? 'shell = True'のないリストではうまくいくと思います。 – zondo

+0

@zondoは窓にはない、いいえ。 Linux yay – Roman

+0

も参照してください。http://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess – tripleee

答えて

0

cpinternal commandではないため、shell=Truethough you might need to specify a full path to cp.exe)は必要ありません。

Windows上で新しいサブプロセスを開始するための内部インターフェイスは、文字列を使用します。つまり、コマンドラインの解釈方法は特定のアプリケーションに依存します。 The default MS C runtime rules (imlemented in subprocess.list2cmdline() that is called implicitly if you pass a list on Windows)は、この場合には正常に動作する必要があります:

#!/usr/bin/env python 
from subprocess import check_call 

check_call(['cp', 'test 123', 'test123']) 

あなたがshell=Trueを使用したい場合は、コマンドラインを解釈するプログラムがcmd.exeであり、あなたがそのエスケープルール(e.g., ^ is a meta-character)を使用しているとして、文字列のようにコマンドを渡す必要があります(あなたがWindowsコンソールでそれを見るように):

check_call('copy /Y /B "test 123" test123', shell=True) 

もちろん、あなたがcopy a file in Pythonに、外部プロセスを起動する必要はありません。

import shutil 

shutil.copy('test 123', 'test123') 
Ubuntuのため
0

:Windows用

subprocess.check_output(['list', 'of', 'commands with spaces']) 

:私はshell=Trueを必要としない情報のため

subprocess.check_output('single command "string with spaces"') 

感謝。

関連する問題