简体   繁体   English

我如何使用 python 脚本中的命令行

[英]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.

相关问题 如何从Python脚本启动GIMP命令行? - How can i launch the GIMP command line from a Python script? 我如何使用python从命令行部署代理 - how can i use python to deploy proxies from the command line 如何从命令行使用qsub和Python? - How can I use qsub with Python from the command line? 如何在命令行中使用 Python 脚本而无需 cd-ing 到其目录? 是 PYTHONPATH 吗? - How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH? 我可以从命令行运行python脚本的一部分吗? - Can I run a portion of a python script from command line? 如何从 python 解释器命令行获取 python 脚本路径? - How can I get the python script path from a python interpreter command line? 如何使用./ 通过 Python 脚本执行命令行程序? - How can I execute command line program with ./ via a Python script? 如何将 python 脚本的结果传递给命令行? - How can I pass the result of a python script to the command line? 如何在没有脚本参数的情况下从命令行启动Python调试器? - How can I start the Python debugger from the command line without a script argument? 如何从命令行Python脚本中保存LibreOffice Calc电子表格中的所有工作表 - How can I save ALL sheets in a LibreOffice Calc Spreadsheet from a command-line Python script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM