Reputation: 712
I wrote the following script called file_I_executed.py
:
import subprocess
def main():
loc = subprocess.popen("pwd")
print loc
Which gave output:
C:\Python27\python.exe C:/Users/username/PycharmProjects/projectname/file_I_executed.py
However, when I try "pwd" on the windows cmd, I get:
C:\Users\username\somedirectory>pwd
'pwd' is not recognized as an internal or external command,
operable program or batch file.
What gives? How does subprocess work, exactly? Why is "pwd" giving me the python path as well as the path of the script, when it clearly should not give me that when I run this from the windows command line?
I am using python 2.7.1 from pycharm, on windows 7.
CLARIFICATION: I am fully aware that "pwd" is not a windows command. However, the script shown above gave me the result I indicated, and I don't understand why.
Upvotes: 4
Views: 1781
Reputation: 11
From: https://docs.python.org/3/library/subprocess.html#module-subprocess
To support a wide variety of use cases, the Popen constructor (and the convenience functions) accept a large number of optional arguments. For most typical use cases, many of these arguments can be safely left at their default values. The arguments that are most commonly needed are:
args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.
However, this is odd since the Popen call should in-fact be upper-case like a recent comment said.
Upvotes: 1
Reputation: 28870
The output you're seeing when you run the program under PyCharm is not coming from the subprocess.popen("pwd")
call. In fact, this call is never being executed at all!
You have a main
function, but you do not have any code that calls main()
.
The output is simply PyCharm's default printout when it starts your program. You will get the same output with an empty program. If you run your program from the command line there will be no output.
If you add a main()
call to the bottom of the file, you will get an error when it tries to execute subprocess.popen("pwd")
, because there is no such function.
If you change it to the correct subprocess.Popen("pwd")
you will then get the expected error that there is no pwd
command. (Thanks anarchos78 for pointing this out.)
PyCharm has an integrated debugger which can help troubleshoot things like this. By stepping through the code, you can easily see which parts of the code are executed or not.
Upvotes: 2
Reputation:
pwd
is a linux command, not a Windows command. In Windows you can use echo %cd%
.
Upvotes: 2