[英]How can i use command line from python script
I already tried with我已经尝试过
import os
os.system('do stuff')
but i need this to "save the state of what it has done" for example:但我需要这个来“保存它所做的 state”,例如:
os.system('dir')
os.system('cd ..')
os.system('dir')
In this code, the dir will return the same thing, because the cd..
does not apply.在这段代码中,dir 将返回相同的内容,因为
cd..
不适用。 how can i do something like that?我怎么能做这样的事情?
I also need to store the output in a variable.我还需要将 output 存储在一个变量中。
I wouldn't use os.system
to check the contents of a directory, instead use os.listdir()
and os.chdir()
.我不会使用
os.system
来检查目录的内容,而是使用os.listdir()
和os.chdir()
。
initial_state = os.listdir()
os.chdir("..")
one_dir_up_state = os.listdir()
os.system function uses the current process of your running program and replaces the image of it with the "dir" program image, therefore your code after the call to the dir program will not be executed and discarded. os.system function 使用您正在运行的程序的当前进程,并将其映像替换为“dir”程序映像,因此您调用 dir 程序后的代码将不会被执行和丢弃。 To overcome this you can create a new process:
为了克服这个问题,您可以创建一个新流程:
import os
from multiprocessing import Process
def dir():
os.system("dir")
def dir2():
# we can pass .. as an argument instead of running "cd ..""
os.system("dir ..")
if __name__ == '__main__':
p1 = Process(target=dir)
p1.start()
p1.join()
p2 = Process(target=dir2)
p2.start()
p2.join()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.