我想替换这个BASH表达式:
expr $COUNT + 1 > $COUNT_FILE
与Python中的等价物。我想出了这个:
subprocess.call("expr " + str(int(COUNT)+1) + " > " + COUNT_FILE, shell=True)
或者(可能更好一点):
subprocess.call("echo " + 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')
答案 0 :(得分:5)
with open(COUNT_FILE, 'w') as f:
f.write(str(int(COUNT)+1)+'\n')
答案 1 :(得分:3)
使用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
块后文件将自动关闭。
答案 2 :(得分:2)
不要使用shell,使用Python的I / O函数直接写入文件:
with open(count_file, 'w') as f:
f.write(str(count + 1) + '\n')
with
语句随后会关闭文件,因此更安全。
答案 3 :(得分:2)
如果需要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