为什么python程序无法运行_为什么我的python子流程代码无法正常工作?

from subprocess import *

test = subprocess.Popen('ls')

print test

When i try to run this simple code, I get an error window saying:

WindowsError: [Error 2] The system cannot find the file specified

I have no clue why I can't get this simple code to work and it's frustrating, any help would be greatly appreciated!

解决方案

It looks like you want to store the output from a subprocess.Popen() call.

For more information see Subprocess - Popen.communicate(input=None).

>>> import subprocess

>>> test = subprocess.Popen('ls', stdout=subprocess.PIPE)

>>> out, err = test.communicate()

>>> print out

fizzbuzz.py

foo.py

[..]

However Windows shell (cmd.exe) doesn't have a ls command, but there's two other alternatives:

Use os.listdir() - This should be the preffered method since it's much easier to work with:

>>> import os

>>> os.listdir("C:\Python27")

['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe

', 'pythonw.exe', 'README.txt', 'tcl', 'Tools', 'w9xpopen.exe']

Use Powershell - Installed by default on newer versions of Windows (>= Windows 7):

>>> import subprocess

>>> test = subprocess.Popen(['powershell', '/C', 'ls'], stdout=subprocess.PIPE)

>>> out, err = test.communicate()

>>> print out

Directory: C:\Python27

Mode LastWriteTime Length Name

---- ------------- ------ ----

d---- 14.05.2013 16:00 DLLs

d---- 14.05.2013 16:01 Doc

[..]

Shell commands using cmd.exe would be something like this:

test = subprocess.Popen(['cmd', '/C', 'ipconfig'], stdout=subprocess.PIPE)

Notes:

Do not use shell=True as it is a security risk.

For more information see Why not just use shell=True in subprocess.Popen in Python?

Do not use from module import *. See why in Language Constructs You Should Not Use

It doesn't even serve a purpose here, when you use subprocess.Popen().

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值