Python shell脚本无法与源命令一起执行

ltskdhd1  于 2023-08-07  发布在  Shell
关注(0)|答案(1)|浏览(125)

我想使用subprocess.Popen()从python脚本调用bash脚本。将shell脚本作为可执行文件调用是可行的,但是source不能。为什么?为什么?
文件 test_python.py

import sys
import os
import subprocess

os.putenv("testvar", "testvalue")

test = subprocess.Popen("./test_shell.sh", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print(test)
test = subprocess.Popen(". test_shell.sh", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print(test)
test = subprocess.Popen("source test_shell.sh", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print(test)
test = subprocess.Popen("/bin/bash test_shell.sh", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print(test)
test = subprocess.Popen("/bin/sh test_shell.sh", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print(test)

字符串
文件 test_shell.sh

#!/bin/bash

echo "$testvar"


python test_python.py的输出:

('testvalue\n', '')
('', '/bin/sh: .: test_shell.sh: cannot open [No such file or directory]\n')
('', '/bin/sh: .: test_shell.sh: cannot open [No such file or directory]\n')
('testvalue\n', '')
('testvalue\n', '')

kxe2p93d

kxe2p93d1#

将shell脚本作为可执行文件调用是可行的,而将其作为源文件则不行。
您正在呼叫./test_shell.sh。但是,您可以源代码test_shell.sh
为什么?为什么?
因为PATH中没有这样的脚本
如果你想获得./test_shell.sh的源代码,那么就选择source ./test_shell.sh,而不是source test_shell.sh

相关问题