linux上python中“导出"的子进程模块错误? [英] Subprocess module errors with 'export' in python on linux?

查看:30
本文介绍了linux上python中“导出"的子进程模块错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设置一个程序来将我的计算机连接到我们学校的代理服务器,目前有这样的事情:

I'm setting up a program to connect my computer to our schools proxy and currently have something like this:

import subprocess
import sys

username = 'fergus.barker'
password = '*************'
proxy = 'proxy.det.nsw.edu.au:8080'
options = '%s:%s@%s' % (username, password, proxy)

subprocess.Popen('export http_proxy=' + options)

但是在运行时我得到:

Traceback (most recent call last):
File "school_proxy_settings.py", line 19, in <module>
 subprocess.Popen('export http_proxy=' + options)
File "/usr/lib/python2.6/subprocess.py", line 621, in __init__
 errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1126, in _execute_child
 raise child_exception
OSError: [Errno 2] No such file or directory

为什么会这样?

推荐答案

问题在于 export 不是实际的命令或文件.它是像 bashsh 这样的 shell 的内置命令,所以当你尝试一个 subprocess.Popen 时你会得到一个异常,因为它找不到 export 命令.默认情况下,Popen 执行 os.execvp() 来生成一个新进程,这将不允许您使用 shell 内在函数.

The problem is that export is not an actual command or file. It is a built-in command to shells like bash and sh, so when you attempt a subprocess.Popen you will get an exception because it can not find the export command. By default Popen does an os.execvp() to spawn a new process, which would not allow you to use shell intrinsics.

您可以执行类似的操作,但您必须将调用更改为 Popen.

You can do something like this, though you have to change your call to Popen.

http://docs.python.org/library/subprocess.html

您可以指定 shell=True 使其使用 shell 命令.

You can specify shell=True to make it use shell commands.

class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=无,universal_newlines=False,startupinfo=None,creationflags=0)

在 Unix 上,shell=True:如果 args 是字符串,则指定要通过 shell 执行的命令字符串.这意味着字符串的格式必须与在 shell 提示符下键入时完全相同.例如,这包括引用或反斜杠转义其中包含空格的文件名.如果 args 是一个序列,则第一项指定命令字符串,任何附加项都将被视为 shell 本身的附加参数.也就是说,Popen 的作用相当于:

On Unix, with shell=True: If args is a string, it specifies the command string to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That is to say, Popen does the equivalent of:

Popen(['/bin/sh', '-c', args[0], args[1], ...])

这篇关于linux上python中“导出"的子进程模块错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆