[英]python 3: How to source a bash script and run it in same shell
i am trying to source a shell script having functions.我正在尝试获取具有功能的 shell 脚本。 than trying to execute it like below.
而不是像下面那样尝试执行它。
source ~/abc.sh; abc arg1 arg2 arg3 arg4a
It works in unix shell.它在 unix shell 中工作。 But when I am trying to execute same from inside python script it is giving error
但是当我试图从 python 脚本内部执行相同的操作时,它会给出错误
def subprocess_cmd(command):
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
return proc_stdout
command = "bash -c source ~/abc.sh; abc arg1 arg2 arg3 arg4a"
out = subprocess_cmd(command)
print(out)
when i am executing above python code, it is giving below error.当我在 python 代码上方执行时,它给出了以下错误。
~/abc.sh: line 0: source: filename argument required
source: usage: source filename [arguments]
/bin/sh: line 1: abc: command not found
From Popen reference:来自Popen参考:
On POSIX with shell=True, the shell defaults to /bin/sh.
在 shell=True 的 POSIX 上,shell 默认为 /bin/sh。 If args is a string, the string specifies the command to execute through the shell.
如果 args 是字符串,则该字符串指定要通过 shell 执行的命令。 This means that the string must be formatted exactly as it would be when typed at the shell prompt.
这意味着字符串的格式必须与在 shell 提示符下键入时的格式完全相同。 This includes, for example, quoting or backslash escaping filenames with spaces in them.
这包括,例如,引用或反斜杠转义文件名,其中包含空格。
So what you're passing has to be passed as a single shell command.因此,您传递的内容必须作为单个 shell 命令传递。
When I run your single POSIX shell command in my shell:当我在我的 shell 中运行你的单个 POSIX shell 命令时:
$ bash -c source ~/abc.sh; abc arg1 arg2 arg3 arg4a
~/abc.sh: line 0: source: filename argument required
source: usage: source filename [arguments]
bash: abc: command not found
So there's nothing special about python here.所以这里的python没有什么特别之处。
You get this error because this command amounts to:您会收到此错误,因为此命令相当于:
abc.sh
abc.sh
abc
now available in the new bash shellabc
现在在新的 bash shell 中可用abc
abc
What you want to do is:你想做的是:
abc.sh
abc.sh
abc
now available in the new bash shellabc
现在在新的 bash shell 中可用abc
abc
So you want the following 2 commands in the same shell:因此,您希望在同一个 shell 中使用以下 2 个命令:
source ~/abc.sh
abc arg1 arg2 arg3 arg4a
Namely:即:
bash -c 'source ~/abc.sh; abc arg1 arg2 arg3 arg4a'
(note where the single quotes are.) (注意单引号在哪里。)
In python:在蟒蛇中:
def subprocess_cmd(command):
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
return proc_stdout
command = "bash -c 'source ~/abc.sh; abc arg1 arg2 arg3 arg4a'"
out = subprocess_cmd(command)
print(out)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.