我想使用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', '')
型
1条答案
按热度按时间kxe2p93d1#
将shell脚本作为可执行文件调用是可行的,而将其作为源文件则不行。
您正在呼叫
./test_shell.sh
。但是,您可以源代码test_shell.sh
。为什么?为什么?
因为PATH中没有这样的脚本
如果你想获得
./test_shell.sh
的源代码,那么就选择source ./test_shell.sh
,而不是source test_shell.sh
。