简体   繁体   English

在Windows计算机上从Python运行Linux命令

[英]Running Linux Commands from Python on Windows Computer

I am trying to learn how to run command line commands from Python. 我正在尝试学习如何从Python运行命令行命令。 I am able to do this with DOS: 我可以使用DOS来做到这一点:

import subprocess
subprocess.call("dir",shell=True)

This is fine, but I need to be able to do this for linux commands because my company uses linux servers. 很好,但是我需要对linux命令执行此操作,因为我的公司使用linux服务器。 I am using Mobaxterm to run a local linux session. 我正在使用Mobaxterm运行本地linux会话。 When I try this: 当我尝试这个:

import subprocess
subprocess.call("ls",shell=True)

I get this error from the terminal: 我从终端收到此错误:

'ls' is not recognized as an internal or external command, operable program or batch file.

Which sounds ridiculous to me, because ls is clearly a linux command. 这对我来说听起来很荒谬,因为ls显然是linux命令。

If I don't include shell=True I get this error: 如果我不包含shell=True ,则会出现此错误:

Traceback (most recent call last):
  File "ConsolePractice.py", line 4, in <module>
subprocess.call("ls")
File "C:\Users\my_username\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 560, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Users\my_username\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 950, in __init__
restore_signals, start_new_session)
File "C:\Users\my_username\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 1220, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

So what am I doing wrong? 那我在做什么错? How can I get this to work? 我该如何工作?

EDIT: Thanks for the comments. 编辑:感谢您的评论。 Python for Windows won't work for what I'm trying to do. 适用于Windows的Python无法满足我的要求。 I connected to a linux server and did: 我连接到Linux服务器并执行以下操作:

cat > ConsoleCmd.py
import subprocess
subprocess.call("ls",shell=True)
^C
python ConsoleCmd.py

... and ls ran. ...而ls跑了。 Found the issue. 找到了问题。 I'll just have to get my scripts on to the server and run them from there. 我只需要将脚本放到服务器上并从那里运行它们即可。 Thanks everyone 感谢大家

通过在Mobaxterm中打开SFTP会话 ,将python文件传输到服务器,然后直接在服务器上运行该文件(在服务器上已经安装了python),我能够解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM