英文:
Python shell script cannot be executed with source command
问题
我想使用`subprocess.Popen()`从Python脚本中调用一个bash脚本。调用shell脚本作为可执行文件是有效的,但是使用`source`命令则不行。为什么?
***test_python.py***文件:
```python
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: 无法打开文件 [文件或目录不存在]\n')
('', '/bin/sh: .: test_shell.sh: 无法打开文件 [文件或目录不存在]\n')
('testvalue\n', '')
('testvalue\n', '')
英文:
I want to call a bash script from a python script using subprocess.Popen()
. Calling the shell script as an executable works, but source
ing it does not. Why?
File 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)
File test_shell.sh:
#!/bin/bash
echo "$testvar"
Output of 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
得分: 1
调用shell脚本作为可执行文件是有效的,但作为源码是无效的。
你正在调用
./test_shell.sh
。然而,你使用test_shell.sh
作为源码。为什么?
因为在PATH中没有这样的脚本。
如果你想要源码
./test_shell.sh
,那么应该使用source ./test_shell.sh
而不是source test_shell.sh
。
英文:
> Calling the shell script as an executable works, sourceing it does not.
You are calling ./test_shell.sh
. Yet, you source test_shell.sh
.
> Why?
Because there is no such script in PATH
If you want to source ./test_shell.sh
then source ./test_shell.sh
not source test_shell.sh
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论