Linux,Python开放终端运行全局python命令 [英] Linux, Python open terminal run global python command

查看:75
本文介绍了Linux,Python开放终端运行全局python命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定是否可行.我有一组python脚本,并已在〜/.bashrc中修改了linux PATH,以便每当打开终端时,都可以将python脚本作为命令运行.

Not sure if this is possible. I have a set of python scripts and have modified the linux PATH in ~/.bashrc so that whenever I open a terminal, the python scripts are available to run as a command.

export PATH=$PATH:/home/user/pythonlib/

my_command.py位于上述路径中.

my_command.py resides in the above path.

我可以在终端的任何地方运行my_command.py(args),它将运行python脚本.

I can run my_command.py (args) from anywhere in terminal and it will run the python scripts.

我想通过其他python脚本控制此功能,因为这将是使我的处理例程自动化的最快解决方案.因此,我需要它来打开终端并从我正在使用的python脚本中运行my_command.py(args).

I'd like to control this functionality from a different python script as this will be the quickest solution to automating my processing routines. So I need it to open a terminal and run my_command.py (args) from within the python script I'm working on.

我尝试了子流程:

import subprocess
test = subprocess.Popen(["my_command.py"], stdout=subprocess.PIPE)
output = test.communicate()[0]

虽然my_command.py通常在我启动的任何终端中都可用,但是在这里我无权访问它,找不到返回的文件.

While my_command.py is typically available in any terminal I launch, here I have no access to it, returns file not found.

我可以使用os启动一个新终端,然后输入my_command.py,它可以正常工作

I can start a new terminal using os then type in my_command.py, and it works

os.system("x-terminal-emulator -e /bin/bash")

那么,有没有一种方法可以获取第二种方法来接受要使用args从python运行的脚本?

So, is there a way to get the second method to accept a script you want to run from python with args?

Ubuntu 16

Ubuntu 16

谢谢:)

推荐答案

Popen不会为您在python脚本中创建的会话加载系统PATH.您必须在会话中修改PATH,以将目录包含到您的项目中,如下所示:

Popen does not load the system PATH for the session you create in a python script. You have to modify the PATH in the session to include the directory to your project like so:

someterminalcommand = "my_command.py (args)"

my_env = os.environ.copy()
my_env["PATH"] = "/home/usr/mypythonlib/:" + my_env["PATH"]

combine = subprocess.Popen(shlex.split(someterminalcommand), env=my_env)

combine.wait()

这使我可以从另一个python会话运行"my_command.py"文件,就像打开终端窗口一样.

This allows me to run my "my_command.py" file from a different python session just like I had a terminal window open.

这篇关于Linux,Python开放终端运行全局python命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆