os.system 在 Python 中不起作用

2022-01-23 00:00:00 python command system dos

问题描述

我正在使用 windows vista,但我正在从 DOS 命令运行 python.我有这个简单的 python 程序.(其实就是一个名为test.py的py文件)

I'm working on windows vista, but I'm running python from DOS command. I have this simple python program. (It's actually one py file named test.py)

import os
os.system('cd ..')

当我从 Dos 命令执行python test.py"时,它不起作用.例如,如果执行前的提示 Dos Command 是这样的:

When I execute "python test.py" from a Dos command, it doesn't work. For example, if the prompt Dos Command before execution was this:

C:Directory>

执行后,一定是这样的:

After execution, must be this:

C:>

请帮忙.


解决方案

首先,你一般不想使用 os.system - 看看 子进程模块.但是,这并不能解决您的直接问题(只是您可能遇到的一些问题)- cd 不起作用的实际原因是因为它更改了 subprocess<的工作目录/em>,并且不会影响 Python 正在运行的进程 - 为此,请使用 os.chdir.

First, you generally don't want to use os.system - take a look at the subprocess module instead. But, that won't solve your immediate problem (just some you might have down the track) - the actual reason cd won't work is because it changes the working directory of the subprocess, and doesn't affect the process Python is running in - to do that, use os.chdir.

相关文章