我正在处理一个函数,该函数生成一个随机文件,然后打印它;目前,我有以下代码:
import os
import random
def randomfile(path):
files = os.listdir(path)
index = random.randrange(0, len(files))
return files[index]
pick = randomfile("~/me/Desktop/files")
os.system("cat",pick) # Here i want to execute cat with the random file generated基本上,我只想打印生成的文件,如何将它传递给os.system?
发布于 2022-05-25 23:42:27
@Barmar感谢,伙计,我已经使用了子进程subprocess.run(["cat", pick]),也print (open(pick).read()),它为我工作,再次感谢
发布于 2022-05-25 23:45:43
您可以将其全部添加到os.system中,如os.system('cat' + pick)。另一个选项是使用子进程模块并运行subprocess.check_output("cat", pick)。subprocess.check_output确实会返回一个值,因此您需要将其打印到屏幕上,或者根据您想要使用它做什么来对返回值进行一些操作。
发布于 2022-05-26 00:00:23
可以使用for-循环执行数组中的所有命令:
array = ['cat', 'pick']
for command in array:
os.system(command)https://stackoverflow.com/questions/72385156
复制相似问题