Python linux which command

How do I control which command is when i type python in the shell

I use anaconda as a way to handle virtual environments. This means I have multiple version of python installed. I experience that the wrong python version starts when I run python from the shell. Running

Which python /anaconda3/envs/dash-two/bin/python 
type -a python python is /anaconda3/envs/dash-two/bin/python python is /usr/bin/python 

Which is the «right» and which is the «wrong» python /anaconda3/envs/dash-two/bin/python or /usr/bin/python ?

I solved the problem: My .bash_profile script had these two lines: export PATH=»$PATH:~/bin» export PATH=»/opt/local/bin:/opt/local/sbin:$PATH» When calling .bash_profile more than once it would keep adding to the path. The built in terminal in VS Code copies you path and runs the the .bash_profile script so starting it has the same effect as running .bash_profile twice. The problem was that all since all lines referred to the old $PATH variable it would just keep growing. Adding this export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin at the start solved it.

3 Answers 3

It seems you want to use virtual environments but have not activated one. To do that (assuming you have the basic venv stuff installed — works better for python3)

$ mkdir pytry $ python3 -m virtualenv pytry 

Now you should have a virtual env directory in pytry . cd into pytry and you should see for example

$ ls bin include lib local share $ 

Note run above from the virtual env directory (in our case pytry )

Now you should find that your prompt should have changed from (say) $ to (pytry) $

And which python will tell you your python executable

If you want a different executable then at the time of creation of the venv you need to run instead of

python3 -m virtualenv pytry 
python3 -m virtualenv -p other_python_executable pytry 

In general this will show help

This is controlled in the «PATH» environment variable.

PATH is a list of directories to search in order for the command you’ve typed. It’s a single string seperated by colons. Eg: anything I’ve placed in my home directory ( /home/philip/bin ) will be used instead of anything in /usr/bin/ because my PATH is set to:

echo $PATH /home/philip/bin:/usr/local/bin:/usr/bin:/bin:/usr/games 

To temporarily change your path you can set it with «export». Eg:

export PATH=/usr/local/bin:/usr/bin:/bin:/usr/games:/home/philip/bin 

To set this permanently you will need to set it in your profile. This can be done by putting a line similar to the one above (with your re-ordered path) into a file in your home directory called .profile . If that doesn’t exist, just created it and add the line.

Читайте также:  How to make link image in html

Источник

The which Command in Python

The which Command in Python

  1. Use the shutil.which() Function to Emulate the which Command in Python
  2. Create a Function to Emulate the which Command in Python

In Linux, we have the which command. This command can identify the path for a given executable.

In this tutorial, we will emulate this command in Python.

Use the shutil.which() Function to Emulate the which Command in Python

We can emulate this command in Python using the shutil.which() function. This function is a recent addition in Python 3.3. The shutil module offers several functions to deal with the operations on files and to their collections.

The shutil.which() function returns the path of a given executable, which would run if cmd was called.

import shutil print(shutil.which("python")) 

In the above example, the shutil.which() returns the directory of the Python executable.

Create a Function to Emulate the which Command in Python

Below Python 3.3, there is no way to use the shutil.which() function. So here, we can create a function using functions from the os module ( os.path.exists() ) and os.access methods) to search for the given executable and emulate the which command.

import os def which(pgm):  path=os.getenv('PATH')  for p in path.split(os.path.pathsep):  p=os.path.join(p,pgm)  if os.path.exists(p) and os.access(p,os.X_OK):  return p  print(which("python.exe")) 

Источник

Команда which в Linux [с примерами]

Как улучшить время запуска приложений в Linux

К оманда which в Linux используется для поиска любой команды в Linux. Команда — это исполняемый файл, который вы можете запустить. Команда which находит исполняемый файл в пути поиска вашей оболочки.

Другими словами, если вам интересно, где именно находится определенная программа, просто используйте which. Команда Linux имеет простой синтаксис:

Давайте посмотрим, как использовать эту простую, но полезную команду.

Linux, Примеры команды which

Допустим, вы хотите знать, где находится исполняемый файл Java, используйте команду:

destroyer@andreyex:~$ which java
/usr/bin/java

Обратите внимание, что работает только с исполняемыми файлами. Таким образом, вы должны использовать which только с аргументом. Например, вы устанавливаете Java с помощью пакета JDK, но не запускаете команду с именем «jdk», вы запускаете «java». Таким образом, вы используете команду which на Java, а не JDK.

Если команда which не находит исполняемый файл в текущем пути, она ничего не возвращает.

Использование команды which с несколькими исполняемыми файлами

Вы можете предоставить более одного аргумента для команды which:

which man java python nada

destroyer@andreyex:~$ which man java python nada
/usr/bin/man
/usr/bin/java
/usr/bin/python

Вы заметили что-то здесь? Мы дали ему четыре аргумента, но результат отображается только для трех из них. Это потому, что «nada» не исполняемый файл. Там нет вывода для which.

Читайте также:  Python draw confusion matrix

Показать все пути с командой which

Команда which в Linux имеет только одну опцию -a. По умолчанию эта команда печатает только один путь для своих аргументов.

Если программа имеет исполняемый файл в двух местах, например, в /usr/bin/program и в /usr/local/bin/program, вы можете отобразить оба пути с помощью опции -a.

Статус вывода команды which

Если вы используете команду which в скрипте bash, вам может потребоваться узнать ее состояние завершения.

Команда which имеет следующий статус выхода:

  • 0 — все аргументы найдены и выполняются
  • 1 — один или несколько аргументов не существуют или не выполняются
  • 2 — если указан неверный параметр

Это все, что вам нужно знать о команде which в Linux. Если у вас есть вопросы или предложения, дайте нам знать в комментариях ниже.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

How to Run Python Scripts in Linux

Python is one of the most popular programming languages of all. It’s an interpreted, object-oriented, high-level programming language that features dynamic semantics. If you’re using Linux, then you’ll come across Python scripts quite frequently.

One of the most basic and crucial things to learn is running a Python script when learning or working with Python. Because Python is an interpreted language, it requires the Python interpreter to execute any Python code. Depending on the type of script, there are a couple of ways you can execute it.

This guide will showcase executing a sample Python script.

Python scripts

Any script is a text file containing the code. The file can then be run using an interpreter. The same goes for any Python script.

Generally, a Python script will have the file extension PY. However, there’s another way of writing a Python script: embedding Python codes into a bash script.

Either way, you need to have the Python package installed in your system. Because it’s a popular programming language, all Linux distros offer pre-built Python binaries directly from the official package servers. Distros like Ubuntu, Linux Mint, Pop! OS etc., comes with Python pre-installed. The package name should be “python” or “python3″ for any other distros”.

Working with a Python script

Creating a sample Python script

For demonstration, let’s make a quick Python script. Open up the terminal and create a file named sample-script.py.

To be able to run the script, it must be marked as an executable file. Mark the file as an executable.

Check the file permission to verify if it worked.

Writing a sample Python code

Now, we’re going to put some code in the script. Open up the file in any text editor. For demonstration, I’m going to be using the nano text editor.

We’ll place a simple program that prints “hello world” on the console screen.

Save the file and close the editor.

Running the Python script

Finally, we can run the script. Call the Python interpreter and pass the location of the file.

Читайте также:  Java collection contains null

Bash-style Python script

So far, we’ve seen the default way of running a Python script. However, there’s an unconventional way of writing and running a Python script as a shell script.

Generally, a shell script contains a list of commands that are interpreted and executed by a shell (bash, zsh, fish shell, etc.). A typical shell script uses shebang to declare the desired interpreter for the script.

We can take this structure to our advantage. We’ll declare the Python interpreter as the desired interpreter for our code. The body of the script will contain the desired Python scripts. Any modern shell will execute the script with the Python interpreter.

The structure will look something like this.

Location of Python interpreter

The shebang requires the path of the interpreter. It will tell the shell where to look for the interpreter. Generally, a Python interpreter is available as the command “python” or “python3”. Python 2 is deprecated, so it’s not recommended to use it anymore (except in very specific situations).

To find the location of the Python interpreter, use the which command. It finds the location of the binary of a command.

Creating a shell script

Similar to how we created the Python script, let’s create an empty shell script.

Mark the script as an executable file.

Writing a sample shell script

Open the script file in a text editor.

First, introduce the shebang with the location of the interpreter.

We’ll write a simple Python program that prints “hello world” on the next line.

Save the file and close the editor.

Running the script

Run the script as you’d run a shell script.

Final thought

It needs to be passed on to the interpreter to run a Python code. Using this principle, we can use various types of scripts to run our Python code. This guide demonstrated running Python scripts directly (filename.py scripts) or indirectly (filename.sh).

In Linux, scripts are generally used to automate certain tasks. If the task needs to be repeated regularly, it can also be automated with the help of crontab. Learn more about using crontab to automate various tasks.

About the author

Sidratul Muntaha

Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.

Источник

Python linux which command

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью