用Python编写简单的Bash文件

用Python编写简单的Bash文件,python,bash,file-io,Python,Bash,File Io,我要替换此BASH表达式: expr $COUNT + 1 > $COUNT_FILE 与Python中的等效。我想到了这个: subprocess.call("expr " + str(int(COUNT)+1) + " > " + COUNT_FILE, shell=True) 或者(可能更好一点): 有更好的方法吗 根据您的输入: def out_to_file(out_string, file_name, append='w'): with open(file_n

我要替换此BASH表达式:

expr $COUNT + 1 > $COUNT_FILE
与Python中的等效。我想到了这个:

subprocess.call("expr " + str(int(COUNT)+1) + " > " + COUNT_FILE, shell=True)
或者(可能更好一点):

有更好的方法吗

根据您的输入:

def out_to_file(out_string, file_name, append='w'):
    with open(file_name, append) as f:
        f.write(out_string+'\n')

使用python编写文件,而不是shell。您的代码没有替换任何bash表达式,您仍然在bash中运行它

相反,请尝试:

with open(COUNT_FILE, 'w') as f:
    f.write(str(int(COUNT) + 1) + "\n")

    # or python 2:
    # print >> f, int(COUNT) + 1

    # python 3
    # print(int(COUNT) + 1, file=f)

退出
with
块后,文件将自动关闭。

不要使用shell,使用Python的I/O函数直接写入文件:

with open(count_file, 'w') as f:
    f.write(str(count + 1) + '\n')

with
语句负责在以后关闭文件,因此更安全。

如果需要
expr
计算结果,Python指令将是:

import subprocess
count_file= ...   #  It needs to be set somewhere in the Python program
count= ...        #  Idem
subprocess.call(["expr",str(count),"+","1"], stdout=open(count_file,"wb") )
f.close()
如果您喜欢用Python进行计算,可以使用

with open(count_file, 'w') as f:
    f.write(str(count+1)+'\n')
如果要检索环境变量,请执行以下操作:

import os
count_file= os.environ['COUNT_FILE']
count= int( os.environ['COUNT'] )
如果您想使其更通用,还可以使用

count= ...        #  It needs to be set somewhere in the Python program
print( count + 1 )
并在调用Python时执行重定向:

$ myIncrementer.py >$COUNT_FILE

在此之后文件是否关闭?是的,当Python使用-block离开
时,会自动关闭文件。@AnttiHaapala感谢Antti。更正。我的意思是它不是用expr@AnttiHaapala天哪,你完全正确。我在头脑中发明/纠正了50%的指令。谢谢你的帮助!把这个扔出去。。。您展示的第三种方法(Python3版本)可以通过Python2访问,方法是在文件顶部抛出一个来自_future _uuuimport print_函数的
。我相信你已经知道了,但不确定行动是否知道。
count= ...        #  It needs to be set somewhere in the Python program
print( count + 1 )
$ myIncrementer.py >$COUNT_FILE