将“源"称为“源".来自subprocess.Popen的命令 [英] Calling the "source" command from subprocess.Popen

查看:99
本文介绍了将“源"称为“源".来自subprocess.Popen的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用source the_script.sh调用的.sh脚本.定期调用此方法是可以的.但是,我试图通过subprocess.Popen从我的python脚本中调用它.

I have a .sh script that I call with source the_script.sh. Calling this regularly is fine. However, I am trying to call it from my python script, through subprocess.Popen.

从Popen调用它,在以下两个场景调用中出现以下错误:

Calling it from Popen, I am getting the following errors in the following two scenario calls:

foo = subprocess.Popen("source the_script.sh")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/subprocess.py", line 672, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1213, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory


>>> foo = subprocess.Popen("source the_script.sh", shell = True)
>>> /bin/sh: source: not found

有什么作用?当我可以在python之外访问时,为什么不能从Popen调用源"?

What gives? Why can't I call "source" from Popen, when I can outside of python?

推荐答案

source不是可执行命令,它是内置的shell.

source is not an executable command, it's a shell builtin.

使用source的最常见情况是运行更改环境的Shell脚本并将该环境保留在当前Shell中.这就是virtualenv修改默认python环境的工作方式.

The most usual case for using source is to run a shell script that changes the environment and to retain that environment in the current shell. That's exactly how virtualenv works to modify the default python environment.

创建子流程并在子流程中使用source可能不会做任何有用的事情,不会修改父流程的环境,使用源脚本的任何副作用都不会发生

Creating a sub-process and using source in the subprocess probably won't do anything useful, it won't modify the environment of the parent process, none of the side-effects of using the sourced script will take place.

Python有一个类似的命令execfile,它使用当前的python全局命名空间(或另一个,如果您提供一个)来运行指定的文件,您可以使用与bash命令source类似的方式.

Python has an analogous command, execfile, which runs the specified file using the current python global namespace (or another, if you supply one), that you could use in a similar way as the bash command source.

这篇关于将“源"称为“源".来自subprocess.Popen的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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