Dag*_*Dag 17 python subprocess
在我的代码中,我有一个类似于这样的行:
rval = subprocess.call(["mkdir",directoryName], shell=True)
Run Code Online (Sandbox Code Playgroud)
我可以检查rval它是否是,0或者1如果它是1,我想以"A subdirectory or file ben already exists."文件格式从命令中获取文本,所以如果我想确保文本是相同的,我可以将它与另一个文件进行比较.
是否有可能有这样的线,但我知道这不起作用
rval = subprocess.call(["mkdir",directoryName], shell=True) >> filename
Run Code Online (Sandbox Code Playgroud)
所以无论命令发生了什么,文本都被捕获filename,并且rval仍然有返回码?
btu*_*bbs 18
子进程模块具有内置的'check_output'功能,用于执行此操作:
In [11]: result = subprocess.check_output(['pwd'])
In [12]: print result
/home/vagrant
Run Code Online (Sandbox Code Playgroud)
Mar*_*som 15
import subprocess
f = open(r'c:\temp\temp.txt','w')
subprocess.call(['dir', r'c:\temp'], shell=True, stdout=f)
f.close()
Run Code Online (Sandbox Code Playgroud)
Jat*_*mar 11
import subprocess
try:
result = subprocess.check_output(['dir', r'c:\temp'], shell=True)
print result
except subprocess.CalledProcessError as e:
return_code = e.returncode
Run Code Online (Sandbox Code Playgroud)
你反正需要使用try catch,因为如果返回代码非零,它会抛出异常:)
| 归档时间: |
|
| 查看次数: |
20579 次 |
| 最近记录: |