[英]Why doesn't my bash script read lines from a file when called from a python script?
I am trying to write a small program in bash and part of it needs to be able to get some values from a txt file where the different files are separated by a line, and then either add each line to a variable or add each line to one array. 我正在尝试用bash写一个小程序,它的一部分需要能够从txt文件中获取一些值,其中不同的文件由一行分开,然后将每一行添加到变量或将每一行添加到一个数组。
So far I have tried this: 到目前为止,我已经尝试过了:
FILE=$"transfer_config.csv"
while read line
do
MYARRAY[$index]="$line"
index=$(($index+1))
done < $FILE
echo ${MYARRAY[0]}
This just produces a blank line though, and not what was on the first line of the config file. 但是,这只会产生一个空白行,而不是配置文件第一行中的内容。
I am not returned with any errors which is why I am not too sure why this is happening. 我没有返回任何错误,这就是为什么我不太确定为什么会这样的原因。
The bash script is called though a python script using os.system("$HOME/bin/mcserver_config/server_transfer/down/createRemoteFolder")
, but if I simply call it after the python program has made the file which the bash script reads, it works. 通过使用
os.system("$HOME/bin/mcserver_config/server_transfer/down/createRemoteFolder")
的python脚本来调用bash脚本,但是如果我只是在python程序制作了bash脚本读取的文件之后调用它,有用。
I am almost 100% sure it is not an issue with the directories, because pwd
at the top of the bash script shows it in the correct directory, and the python program is also creating the data file in the correct place. 我几乎100%确信目录不是问题,因为bash脚本顶部的
pwd
将其显示在正确的目录中,并且python程序也在正确的位置创建数据文件。
Any help is much appreciated. 任何帮助深表感谢。
EDIT: 编辑:
I also tried the subprocess.call("path_to_script", shell=True)
to see if it would make a difference, I know it is unlikely but it didn't. 我还尝试了
subprocess.call("path_to_script", shell=True)
看看是否会有所作为,我知道这不太可能,但没有。
I suspect that when calling the bash script from python, having just created the file, you are not really finished with that file: you should either explicitly close the file or use a with
construct. 我怀疑在刚创建完文件后从python调用bash脚本时,您还没有真正完成该文件:您应该显式关闭文件或使用
with
构造。
Otherwise, the written data is still in any buffer (from the file object, or in the OS, or wherever). 否则,写入的数据仍将位于任何缓冲区中(来自文件对象,OS或任何位置)。 Only closing (or at least flushing) the file makes sure the data is indeed in the file.
仅关闭(或至少刷新)文件才能确保数据确实在文件中。
BTW, instead of os.system
, you should use the subprocess
module... 顺便说一句,而不是
os.system
,您应该使用subprocess
模块...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.